๋ฌธ์
๋ฐฑ์ค ์จ๋ผ์ธ ์ ์ง - 1303๋ฒ
ํ์ด ๊ณผ์
๋ ์ธ๋ ฅ๊ฐ์ ๊ท๋ชจ๋ฅผ ์ธก์ ํ๋ BFS
๋ฌธ์ ์
๋๋ค.W
์ B
๋ก ๋๋์ด์ง ์ปดํฌ๋ํธ์ ํฌ๊ธฐ๋ฅผ ๊ตฌํ๋ฉด ๋๋๋ฐ ์ด๋ BFS
๋ฅผ ํ์ฉํ๊ณ
๊ฐ ์ปดํฌ๋ํธ์ ํฌ๊ธฐ๋ฅผ ๊ตฌํ ๋๋ง๋ค ์ ๊ณฑํ ๊ฐ์ ์ธ๋ ฅ ๊ท๋ชจ์ ๋ํด์ฃผ๋ฉด ๋ฉ๋๋ค.
์ฝ๋
import sys
from collections import deque
N, M = list(map(int, sys.stdin.readline().split()))
board = [list(sys.stdin.readline().strip()) for _ in range(M)]
dx = [0, 0, 1, -1]
dy = [1, -1, 0, 0]
def in_range(x, y):
return 0 <= x < M and 0 <= y < N
def bfs(x, y, visit):
q = deque()
check = 0
q.append([x, y])
visit[x][y] = 1
while q:
x, y = q.popleft()
check += 1
for i in range(4):
nx, ny = x + dx[i], y + dy[i]
if in_range(nx, ny) and board[nx][ny] == board[x][y] and not visit[nx][ny]:
q.append([nx, ny])
visit[nx][ny] = 1
return check
def solution():
warrior = {
'B': [],
'W': []
}
visit = [[0] * N for _ in range(M)]
for x in range(M):
for y in range(N):
if not visit[x][y]:
size = bfs(x, y, visit)
warrior[board[x][y]].append(size)
W = sum(map(lambda x: x**2, warrior['W']))
B = sum(map(lambda x: x**2, warrior['B']))
return f"{W} {B}"
print(solution())
๋ฐ์ํ
'๐ algorithm > boj' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
BOJ 4195 - ์น๊ตฌ ๋คํธ์ํฌ (0) | 2021.03.18 |
---|---|
BOJ 17626 - Four Squares (0) | 2021.03.18 |
BOJ 1260 - DFS์ BFS (0) | 2021.03.18 |
BOJ 6550 - ๋ถ๋ถ ๋ฌธ์์ด (0) | 2021.03.18 |
BOJ 10819 - ์ฐจ์ด๋ฅผ ์ต๋๋ก (0) | 2021.03.18 |
๐ฌ ๋๊ธ