코드
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**6)
n, m = map(int, input().split())
graph = []
for _ in range(m):
graph.append(list(input()))
def dfs(x, y, cnt, color):
graph[x][y] = 0
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if (0 <= nx < m and 0 <= ny < n):
if (graph[nx][ny] == color):
cnt = dfs(nx, ny, cnt+1, color)
return cnt
white = 0
blue = 0
dx = [-1, 1, 0, 0]
dy = [0, 0, 1, -1]
for i in range(m):
for j in range(n):
if(graph[i][j] == 'W'):
white += (dfs(i, j, 1, 'W'))**2
elif(graph[i][j] == 'B'):
blue += (dfs(i, j, 1, 'B'))**2
print(white, blue)
결과
풀이 방법
- DFS를 활용하여 각 색깔의 영역의 크기를 구하여 해결했다.