728x90
[๋ฌธ์ ๋งํฌ] ๐ https://www.acmicpc.net/problem/1303
ํ์ด ๋ฐฉ๋ฒ
๐ก DFS, BFS ์ด์ฉ
๐ ์ฃผ์ํ ์
- ๊ฐ๋ก, ์ธ๋ก ํ์ธํ๊ฐ
Solution
from collections import deque
dx = [1, 0, -1, 0]
dy = [0, -1, 0, 1]
N, M = map(int, input().split())
war = [input().strip() for _ in range(M)]
visited = [[0] * N for _ in range(M)]
W, B = 0, 0
def dfs(i, j, color):
cnt = 1
visited[i][j] = 1
queue = deque()
queue.append((i, j))
while queue:
x, y = queue.popleft()
for k in range(4):
nx = dx[k] + x
ny = dy[k] + y
if 0 <= nx < M and 0 <= ny < N:
if visited[nx][ny] == 0 and war[nx][ny] == color:
visited[nx][ny] = 1
cnt += 1
queue.append([nx, ny])
return cnt
for i in range(M): # ์ธ๋ก
for j in range(N): # ๊ฐ๋ก
if war[i][j] == "W" and visited[i][j] == 0:
W += dfs(i, j, "W") ** 2
elif war[i][j] == "B" and visited[i][j] == 0:
B += dfs(i, j, "B") ** 2
print(W, B)
๊ฐ์ ํ ์
- dfs ํจ์ ์ด๋ฆ ๋ณ๊ฒฝ
- ํจ์ ์ด๋ฆ์ ์ค์ ์ฌ์ฉ ๋ฐฉ์์ธ BFS๋ฅผ ๋ฐ์ํ์ง ์์ผ๋ฏ๋ก, bfs๋ก ๋ณ๊ฒฝํ๋ ๊ฒ์ด ๋ ์ ์ ํ๋ค.
- deque.append์์ ํํ ์ฌ์ฉ
- queue.append([nx, ny]) ๋์ queue.append((nx, ny))๋ก ํต์ผ์ฑ์ ์ ์งํ๋ ๊ฒ์ด ์ข๋ค. ํํ์ ์์ ๋ถ๊ฐ๋ฅ(immutable)ํ๋ฏ๋ก, BFS/DFS์์ ์ขํ ๋ฐ์ดํฐ๋ฅผ ๋ค๋ฃฐ ๋ ์ฃผ๋ก ์ฌ์ฉ๋๋ค.
- ๋ถํ์ํ ์กฐ๊ฑด ๊ฐ์ํ
- if war[i][j] == "W" and visited[i][j] == 0 ๋์ if not visited[i][j]๋ก ์์ํ๊ณ , war[i][j]๋ฅผ ์ธ์๋ก ๋๊ฒจ ๋ฐ๋ณต๋๋ ์กฐ๊ฑด์ ์ค์ผ ์ ์๋ค.
- dx, dy ์ ์ ๊ฐ์ํ
- dx์ dy๋ฅผ ๋ฆฌ์คํธ๋ก ๋๋๊ธฐ๋ณด๋ค, ์ด๋ ๋ฐฉํฅ์ (x, y) ํํ๋ก ๋ฌถ์ผ๋ฉด ๋ ๊ฐ๊ฒฐํ๋ค.
- ์
๋ ฅ ์ฒ๋ฆฌ ์ต์ ํ
- ์ ๋ ฅ๊ฐ์ ์ฒ๋ฆฌํ ๋ strip()์ ๋ถํ์ํ๋ค. input()์ผ๋ก ํ ์ค์ฉ ์ฝ๊ธฐ ๋๋ฌธ์ ๊ณต๋ฐฑ์ด ํฌํจ๋์ง ์๋๋ค.
๊ฐ์ ๋ ์ฝ๋
from collections import deque
directions = [(1, 0), (0, -1), (-1, 0), (0, 1)]
N, M = map(int, input().split())
war = [input() for _ in range(M)]
visited = [[0] * N for _ in range(M)]
W, B = 0, 0
def bfs(i, j, color):
cnt = 1
queue = deque([(i, j)])
visited[i][j] = 1
while queue:
x, y = queue.popleft()
for dx, dy in directions:
nx, ny = x + dx, y + dy
if 0 <= nx < M and 0 <= ny < N and not visited[nx][ny] and war[nx][ny] == color:
visited[nx][ny] = 1
cnt += 1
queue.append((nx, ny))
return cnt
for i in range(M):
for j in range(N):
if not visited[i][j]:
power = bfs(i, j, war[i][j])
if war[i][j] == "W":
W += power ** 2
else:
B += power ** 2
print(W, B)
๐ฉ๐ป ํ๊ณ
๊ฐ๋ก, ์ธ๋ก ๋๋ฌธ์ IndexError๋ฅผ ๊ฒช์๋ค.. ๊ธ์ ์ ํ์ธํ ํ์๊ฐ ์๋ค.
728x90
'๐งฉ Algorithm > [BOJ] Silver' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [BOJ] 11724. ์ฐ๊ฒฐ ์์์ ๊ฐ์ (Python/DFS/Silver 2) (0) | 2026.04.03 |
|---|---|
| [BOJ] 2667. ๋จ์ง๋ฒํธ๋ถ์ด๊ธฐ (Python/DFS/Silver 1) (0) | 2026.04.03 |
| [BOJ] 5212. ์ง๊ตฌ ์จ๋ํ (Python/๊ตฌํ/Silver 2) (0) | 2024.11.07 |
| [BOJ] 5635. ์์ผ (Python/๊ตฌํ/Silver 5) (0) | 2024.11.06 |
| [BOJ] 2563. ์์ข ์ด (Python/๊ตฌํ/Silver 5) (0) | 2024.11.04 |