💡 bfs 새로운 유형 (입력값이 숫자가 아님)

import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
graph = []
normal_cnt = 0
special_cnt = 0
for _ in range(N):
graph.append(list(input().rstrip()))
def bfs(a, b, color, is_special):
dq = deque()
dq.append((a,b,color))
visited[b][a] = True
# 상 하 좌 우
dx = [0,0,-1,1]
dy = [1,-1,0,0]
while dq:
x ,y, color = dq.popleft()
for idx in range(4):
nx = x + dx[idx]
ny = y + dy[idx]
if 0 <= nx < N and 0 <= ny < N and visited[ny][nx] is False:
# 일반인 경우
if is_special == False and color == graph[ny][nx]:
dq.append((nx,ny,graph[ny][nx]))
# 적록색약인 경우
elif is_special == True and (color in ['R','G'] and graph[ny][nx] in ['R','G']):
dq.append((nx,ny,graph[ny][nx]))
elif is_special == True and color == 'B' and color == graph[ny][nx]:
dq.append((nx,ny,graph[ny][nx]))
else:
continue
visited[ny][nx] = True
visited = [[False] * N for _ in range(N)]
# 일반은 빨, 초, 파
for i in range(N):
for j in range(N):
if visited[i][j] == False:
bfs(j, i, graph[i][j], False)
normal_cnt += 1
visited = [[False] * N for _ in range(N)]
# 적록 색약은 빨(R) == 초(G), 파
for i in range(N):
for j in range(N):
if visited[i][j] == False:
bfs(j, i, graph[i][j], True)
special_cnt += 1
print(normal_cnt, special_cnt)
💡 코테 스터디에서 나온 기발한 풀이법
우진
elif is_special == True and (color in 'RG'and graph[ny][nx] in 'RG'):