T = int(input())
graph = [list(input()) for _ in range(T)]
direction = [(-1,0),(1,0),(0,-1),(0,1)]
visited_normal = [[-1]*T for _ in range(T)]
visited_abnormal = [[-1]*T for _ in range(T)]
from collections import deque
def normal(graph,start,visited,p):
visited[start[0]][start[1]]=p
dd = deque([start])
while dd:
x,y = dd.popleft()
for dx,dy in direction:
xx = x+dx ; yy = y+dy
if 0<=xx<T and 0<=yy<T and graph[x][y]==graph[xx][yy] and visited[xx][yy]==-1:
visited[xx][yy]=visited[x][y]
dd.append((xx,yy))
def abnormal_rg(graph,start,visited,q):
visited[start[0]][start[1]]=q
dd = deque([start])
while dd:
x,y = dd.popleft()
for dx,dy in direction:
xx = x+dx ; yy = y+dy
if 0<=xx<T and 0<=yy<T and graph[xx][yy] in ["R","G"] and visited[xx][yy]==-1:
visited[xx][yy]=visited[x][y]
dd.append((xx,yy))
def abnormal_b(graph,start,visited,q):
visited[start[0]][start[1]]=q
dd = deque([start])
while dd:
x,y = dd.popleft()
for dx,dy in direction:
xx = x+dx ; yy = y+dy
if 0<=xx<T and 0<=yy<T and graph[x][y]==graph[xx][yy]=="B" and visited[xx][yy]==-1:
visited[xx][yy]=visited[x][y]
dd.append((xx,yy))
p = 0
for i in range(T):
for j in range(T):
if visited_normal[i][j] == -1:
normal(graph,(i,j),visited_normal,p)
p+=1
q = 0
for i in range(T):
for j in range(T):
if visited_abnormal[i][j] == -1 and graph[i][j] in ['R','G']:
abnormal_rg(graph,(i,j),visited_abnormal,q)
q+=1
elif visited_abnormal[i][j] == -1 and graph[i][j]=="B":
abnormal_b(graph,(i,j),visited_abnormal,q)
q+=1
print(p,q)
풀이
적록색맹이 아닌 사람일 경우, graph의 값을 확인해 visited_normal에 경우의 수 p를 입력하는 normal bfs 함수를 구현했다.
적록색맹인 경우에는 red와 green은 같은 색으로 보고, blue는 다른 색으로 보기 때문에 함수를 분리해서 구현했다.