Notice
Recent Posts
Recent Comments
Link
«   2024/05   »
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
Tags
more
Archives
Today
Total
관리 메뉴

짱이 될거야

백준 1303: 전쟁 - 전투 Python (BFS) 본문

알고리즘

백준 1303: 전쟁 - 전투 Python (BFS)

jeong57 2022. 11. 14. 10:05

 

코드의 중복을 막기 위해서, bfs 함수의 인자로 현재 위치 뿐만 아니라 색도 함께 전달했다.

방문하지 않았으면서 색이 일치하는 것들만 counting 하고, 마지막에 제곱해서 결괏값에 더한다.

from collections import deque
import sys
input = sys.stdin.readline


def bfs(si, sj, color):
    army = 0
    q = deque()
    q.append((si, sj))
    visited[si][sj] = 1

    while q:
        si, sj = q.popleft()
        army += 1
        for di, dj in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
            ni, nj = si+di, sj+dj
            if 0 <= ni < M and 0 <= nj < N and not visited[ni][nj]:
                if arr[ni][nj] == color:
                    q.append((ni, nj))
                    visited[ni][nj] = 1
    return army


N, M = map(int, input().split())    # N: 가로(j), M: 세로(i)
arr = [list(input().rstrip()) for _ in range(M)]
visited = [[0] * N for _ in range(M)]   # 방문체크

result_w = 0
result_b = 0
for i in range(M):
    for j in range(N):
        if not visited[i][j]:
            if arr[i][j] == 'W':
                result_w += (bfs(i, j, 'W') ** 2)
            else:
                result_b += (bfs(i, j, 'B') ** 2)
print(result_w, result_b)

'알고리즘' 카테고리의 다른 글

프로그래머스: 모의고사  (0) 2022.11.22
프로그래머스: 과일장수 Python  (0) 2022.11.15
백준 2581: 소수 Python  (0) 2022.11.11
백준 1292: 쉽게 푸는 문제 Python  (0) 2022.11.10
백준 3184: 양 Python  (0) 2022.11.09
Comments