[백준] 1303번 전쟁 - 전투 (파이썬)

전민기·2023년 9월 26일

https://www.acmicpc.net/problem/1303

from collections import deque

n, m = map(int, input().split())
graph = []
for _ in range(m):
    tmp = list(input())
    graph.append(tmp)
    
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

distance = [[-1]*n for _ in range(m)]

def bfs(x, y, c):
    q = deque()
    q.append([x, y])
    distance[x][y] = 1
    cnt = 1
    
    while q:
        x, y = q.popleft()
        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]
            if nx < 0 or ny < 0 or nx > m-1 or ny > n-1:
                continue
            elif distance[nx][ny] == -1 and graph[nx][ny] == c:
                distance[nx][ny] = 1
                q.append([nx, ny])
                cnt += 1
    return cnt

w = []
b = []

for i in range(m):
    for j in range(n):
        if graph[i][j] == 'W' and distance[i][j] == -1:
            cnt = bfs(i, j, 'W')
            w.append(cnt**2)

for i in range(m):
    for j in range(n):
        if graph[i][j] == 'B' and distance[i][j] == -1:
            cnt = bfs(i, j, 'B')
            b.append(cnt**2)
            
print(sum(w), sum(b))

0개의 댓글