https://www.acmicpc.net/problem/1303
from collections import deque
n, m = map(int, input().split())
arr = [list(input().strip()) for _ in range(m)]
visit = [[0] * n for _ in range(m)]
b, w = [], []
dx, dy = [1, -1, 0, 0], [0, 0, 1, -1]
def bfs(x, y, char):
q = deque()
q.append((x, y))
cnt = 1
visit[x][y] = 1
while q:
x, y = q.popleft()
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if 0 <= nx < m and 0 <= ny < n and visit[nx][ny] == 0 and arr[nx][ny] == char:
visit[nx][ny] = 1 # 방문 체크
cnt += 1
q.append((nx, ny))
return cnt
for i in range(m):
for j in range(n):
if arr[i][j] == 'B' and visit[i][j] == 0:
group = bfs(i, j, 'B')
b.append(group)
if arr[i][j] == 'W' and visit[i][j] == 0:
group = bfs(i, j, 'W')
w.append(group)
w_sum = sum(x**2 for x in w)
b_sum = sum(x**2 for x in b)
print(w_sum, b_sum)
'알고리즘 문제풀이' 카테고리의 다른 글
흙길 보수하기 [백준 1911] (0) | 2025.03.08 |
---|---|
다이어트 [백준 1484] (0) | 2025.02.25 |
양치기 꿍[백준 3187] (0) | 2025.01.30 |
텔레포트 정거장[백준 18232] (0) | 2025.01.29 |
돌다리[백준 12761] (0) | 2025.01.28 |