[BOJ] 10026 - 적록색약

김우경·2020년 12월 19일
0

알고리즘

목록 보기
25/69

와 데박 디버깅 한줄 안찍고 한번에 풀었당 ~ㅋ

문제 링크

적록색약

문제 설명

N*N 크기의 그리드 각 칸에 RGB 하나씩 색칠되어있다. 구역이란 같은 색이 상하좌우 인접한 것을 의미하고, 적록색약을 가진 사람의 경우에는 R과 G를 구분하지 못한다.
그리드를 적록색약인 사람이 봤을 때와 아닌 사람이 봤을 때 구역의 수를 구하라

문제 풀이

  1. 그리드 입력받기
  2. 각 칸을 돌면서 방문하지 않은 칸이면
    2.1 적록색약이 아닌 사람이 봤을때의 구역 bfs로 찾기
    2.2 적록샥약인 사람이 봤을때의 구역 bfs로 찾기

코드

import sys
from collections import deque

input = sys.stdin.readline

N = int(input())
Map = []
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
visited_rgb = [[0]*N for _ in range(N)]
visited_rg = [[0]*N for _ in range(N)]

for _ in range(N):
    Map.append(list(input().strip()))

def in_bound(x,y):
    if x in range(0,N) and y in range(0,N):
        return True
    else:
        return False

def check_rg(rgb1, rgb2):
    if rgb1 == rgb2:
        return True
    elif rgb1 in ('R', 'G') and rgb2 in ('R', 'G'):
        return True
    else:
        return False

def region_for_rgb(i,j):
    queue = deque([(i,j)])
    visited_rgb[i][j] = 1

    while queue:
        x,y = queue.popleft()
        for k in range(4):
            nx, ny = x+dx[k], y+dy[k]
            if in_bound(nx, ny):
                if visited_rgb[nx][ny] == 0 and Map[nx][ny] == Map[x][y]:
                    queue.append((nx, ny))
                    visited_rgb[nx][ny] = 1

def region_for_rg(i,j):
    queue = deque([(i,j)])
    visited_rg[i][j] = 1

    while queue:
        x,y = queue.popleft()
        for k in range(4):
            nx, ny = x+dx[k], y+dy[k]
            if in_bound(nx, ny):
                if visited_rg[nx][ny] == 0 and check_rg(Map[nx][ny], Map[x][y]):
                    queue.append((nx, ny))
                    visited_rg[nx][ny] = 1

count_rgb = 0
count_rg = 0
for i in range(N):
    for j in range(N):
        if visited_rgb[i][j] == 0:
            region_for_rgb(i,j)
            count_rgb += 1
        if visited_rg[i][j] == 0:
            region_for_rg(i,j)
            count_rg += 1

print(count_rgb, count_rg)

    
profile
Hongik CE

0개의 댓글