[백준] 1303번 전쟁 - 전투

거북이·2023년 9월 21일
0

백준[실버1]

목록 보기
59/67
post-thumbnail

💡문제접근

  • BFS 탐색을 진행하면서 "W" 무리와 "B" 무리를 찾고 리턴한 값에 제곱을 취해 병사들의 위력의 합을 구한다.

💡코드(메모리 : 34176KB, 시간 : 76ms)

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

N, M = map(int, input().strip().split())
war = [list(input().strip()) for _ in range(M)]
visited = [[False] * N for _ in range(M)]

def BFS(y, x, flag):
    cnt = 1
    queue = deque()
    queue.append([y, x])
    visited[y][x] = True
    while queue:
        dy = [0, 1, 0, -1]
        dx = [-1, 0, 1, 0]
        y, x = queue.popleft()

        for i in range(4):
            ny = y + dy[i]
            nx = x + dx[i]
            if ny < 0 or ny >= M or nx < 0 or nx >= N:
                continue
            if 0 <= nx < N and 0 <= ny < M:
                if not visited[ny][nx] and war[ny][nx] == flag:
                    visited[ny][nx] = True
                    queue.append([ny, nx])
                    cnt += 1
    return cnt


W_stat = 0
B_stat = 0
for a in range(M):
    for b in range(N):
        if war[a][b] == "W" and not visited[a][b]:
           W_stat += (BFS(a, b, "W") ** 2)
        elif war[a][b] == "B" and not visited[a][b]:
            B_stat += (BFS(a, b, "B") ** 2)
print(W_stat, B_stat)

💡소요시간 : 24m

0개의 댓글