티스토리 뷰

728x90

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

 

1303번: 전쟁 - 전투

첫째 줄에는 전쟁터의 가로 크기 N, 세로 크기 M(1 ≤ N, M ≤ 100)이 주어진다. 그 다음 두 번째 줄에서 M+1번째 줄에는 각각 (X, Y)에 있는 병사들의 옷색이 띄어쓰기 없이 주어진다. 모든 자리에는

www.acmicpc.net

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
from collections import deque
 
 
def bfs(x, y, color):
    cnt = 1
    dq = deque()
    dq.append([x, y])
    visit[x][y] = True
    while dq:
        x, y = dq.popleft()
        for dx, dy in direction:
            nx, ny = x + dx, y + dy
            if 0 <= nx < M and 0 <= ny < N and war_map[nx][ny] == color and not visit[nx][ny]:
                dq.append([nx, ny])
                visit[nx][ny] = True
                cnt += 1
    return cnt * cnt
 
 
N, M = map(int, input().split())
direction = [(01), (10), (0-1), (-10)]
visit = [[False for _ in range(N)] for _ in range(M)]
war_map = []
W, B = 00
for i in range(M):
    war_map.append(list(input().rstrip()))
for i in range(M):
    for j in range(N):
        if war_map[i][j] == 'W' and not visit[i][j]:
            W += bfs(i, j, war_map[i][j])
        elif war_map[i][j] == 'B' and not visit[i][j]:
            B += bfs(i, j, war_map[i][j])
print(W, B)
cs

 

댓글