기록하고 까먹지 말기

1303 본문

전공/백준

1303

yha97 2023. 3. 30. 10:35

날짜 : 2023. 03. 30

사용 언어 : python

 

문제

 

 

코드

import sys
from collections import deque

n, m = map(int, sys.stdin.readline().split())  # 가로, 세로
graph = list()
visited = [[False] * n for _ in range(m)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]


def bfs(a, b, team):
    cnt = 1
    q = deque()
    q.append([a, b])
    while q:
        r, c = q.popleft()
        for i in range(4):
            x = r + dx[i]
            y = c + dy[i]
            if x in range(m) and y in range(n):  # 범위에 포함
                if not visited[x][y] and graph[x][y] == team:  # 방문 안헸고, 같은 팀
                    cnt += 1
                    visited[x][y] = True  # 방문처리
                    q.append([x, y])  # 큐에 포함
    #print(team, cnt ** 2)
    return cnt ** 2


for _ in range(m):
    graph.append(list(sys.stdin.readline().rstrip()))

"""for i in graph:
    print(i)"""

total_blue, total_white = 0, 0
for i in range(m):
    for j in range(n):
        if not visited[i][j]:
            visited[i][j] = True
            if graph[i][j] == "B":
                total_blue += bfs(i, j, "B")
            else:
                total_white += bfs(i, j, "W")

print(total_white, total_blue)

 

 

풀이

- 각 팀을 입력받은 후 방문하지 않은 위치의 팀에 따라 bfs를 실행한 후 연관된 그룹의 인원 명수를 제곱한 값을 리턴함으로써 각 팀의 전투력을 가산한다.

- 전부 방문처리한 이후 그 값들을 출력한다.

 

 

알게된 점

 

 

참고 사이트

 

'전공 > 백준' 카테고리의 다른 글

9019  (0) 2023.04.03
5430  (0) 2023.03.31
1914  (0) 2023.03.29
1647  (0) 2023.03.28
1197  (0) 2023.03.27