๋ฌธ์
https://www.acmicpc.net/problem/1303
ํ์ด
# ๋ฐฑ์ค 1303๋ฒ ๋ฌธ์ - ์ ์-์ ํฌ
from collections import deque
dx, dy = [0,0,-1,1], [1,-1,0,0]
n, m = map(int, input().split())
graph = [list(input()) for i in range(m)]
visited = [[0]*n for j in range(m)]
def bfs(x, y, color):
q = deque()
q.append((x, y))
visited[x][y] = 1
cnt = 1
while q:
x, y = q.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < m and 0 <= ny < n and not visited[nx][ny] and graph[nx][ny] == color:
cnt += 1
visited[nx][ny] = 1
q.append((nx, ny))
return cnt**2
white_cnt = 0
blue_cnt = 0
for i in range(m):
for j in range(n):
if not visited[i][j]:
if graph[i][j] == 'W':
white_cnt += bfs(i, j, 'W')
else:
blue_cnt += bfs(i, j, 'B')
print(white_cnt, blue_cnt)
์ด๋ฒ ๋ฌธ์ ๋ BFS๋ก ์ฝ๊ฒ ํด๊ฒฐ์ด ๊ฐ๋ฅํ ๋ฌธ์ ์๋ค.
์ฒ์์ ์ค๋ฅ๋ ๊ทธ๋ํ๋ฅผ ํ์ํ๋ ์๊ฐ cnt๋ฅผ 1๋ก ๋์ด์ผ ํ๋๋ฐ 0์ผ๋ก ๋์ด์ ๊ฐ์ด ๋ค๋ฅด๊ฒ ๋์๋ค.
์ด ์ค๋ฅ๋ฅผ ํด๊ฒฐ ํ์๋ ๊ณ์ ๋ฐํ์ ์๋ฌ๊ฐ ๋ฌ๋ค.
๊ฐ๋ก, ์ธ๋ก์ ์ธ๋ฑ์ค ์ค์ ์ ์๋ชปํด์ ์ค๋ฅ๊ฐ ๋ฌ๋ ๊ฒ์ด๋ค. ๋ฌธ์ ๋ฅผ ์ ์ฝ๊ณ ์ธ๋ฑ์ค๋ฅผ ์ ํ์ธํ๋๋ก ํด์ผ๊ฒ ๋ค.
'๐๏ธ Algorithm > ๐ฉ ๋ฐฑ์ค' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 14503๋ฒ_๋ก๋ด ์ฒญ์๊ธฐ (0) | 2023.02.10 |
---|---|
๐ฉ [๋ฐฑ์ค] [Python] [Silver4] 1269๋ฒ_๋์นญ ์ฐจ์งํฉ (0) | 2023.02.09 |
๐ฉ [๋ฐฑ์ค] [Python] [Silver1] 2504๋ฒ_๊ดํธ์ ๊ฐ (0) | 2023.02.08 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold5] 1068๋ฒ_ํธ๋ฆฌ (0) | 2023.01.04 |
๐ฉ [๋ฐฑ์ค] [Python] [Gold4] 2573๋ฒ_๋น์ฐ (0) | 2023.01.04 |