[백준][Python] 10026번 적록색약
DFS 풀이
import sys
sys.setrecursionlimit(10000)
def dfs(x,y,graph,color):
global result
visited[x][y] = 1
result += 1
dx = [-1,1,0,0]
dy = [0,0,-1,1]
for i in range(len(dx)):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n:
if visited[nx][ny] == 0 and graph[nx][ny] == color:
dfs(nx,ny,graph,color)
n = int(input())
graph = []
matrix = []
for i in range(n):
row = []
graph.append(list(input()))
for j in range(n):
if graph[i][j] == "G":
row.append("R")
else :
row.append(graph[i][j])
matrix.append(row)
visited = [[0]*n for i in range(n)]
result = 0
cnt_result = 0
for color in ["R","G","B"]:
cnt = []
for i in range(n):
for j in range(n):
if graph[i][j] == color and visited[i][j] == 0:
dfs(i,j,graph,color)
cnt.append(result)
result = 0
cnt_result += len(cnt)
print(cnt_result, end = " ")
result = 0
cnt_result_matrix = 0
visited = [[0]*n for i in range(n)]
for color in ["R","B"]:
cnt = []
for i in range(n):
for j in range(n):
if matrix[i][j] == color and visited[i][j] == 0:
dfs(i,j,matrix,color)
cnt.append(result)
result = 0
cnt_result_matrix += len(cnt)
print(cnt_result_matrix)
BFS 풀이
from collections import deque
n = int(input())
graph = []
matrix = []
for i in range(n):
row = []
graph.append(list(input()))
for j in range(n):
if graph[i][j] == "G":
row.append("R")
else :
row.append(graph[i][j])
matrix.append(row)
def bfs(x,y,graph,color):
queue = deque()
queue.append((x,y))
visited[x][y] == 1
result = 1
dx = [-1,1,0,0]
dy = [0,0,-1,1]
while queue:
x,y = queue.popleft()
for i in range(len(dx)):
nx = x + dx[i]
ny = y + dy[i]
if nx <= -1 or nx >= n or ny <= -1 or ny >= n:
continue
if graph[nx][ny] != color:
continue
if visited[nx][ny] == 0 and graph[nx][ny] == color:
queue.append((nx,ny))
visited[nx][ny] = 1
result += 1
return result
cnt_result = 0
visited = [[0]*n for i in range(n)]
for color in ["R","G","B"]:
cnt = []
for i in range(n):
for j in range(n):
if graph[i][j] == color and visited[i][j] == 0:
cnt.append(bfs(i,j,graph,color))
cnt_result += len(cnt)
print(cnt_result, end = " ")
cnt_result_matrix = 0
visited = [[0]*n for i in range(n)]
for color in ["R","B"]:
cnt = []
for i in range(n):
for j in range(n):
if matrix[i][j] == color and visited[i][j] == 0:
cnt.append(bfs(i,j,matrix,color))
cnt_result_matrix += len(cnt)
print(cnt_result_matrix)