BFS ๋ฌธ์
https://www.acmicpc.net/problem/3055
๐กํ์ด์ฝ๋ (์ฑ๊ณต - BFS)
'''
.: ๋น์ด์๋๊ณณ (๋ฌผ O, ๊ณ ์ด๋์น O)
*: ๋ฌผ (๋ฌผ O, ๊ณ ์ด๋์น X)
X: ๋ (๋ฌผ X, ๊ณ ์ด๋์น X)
D: ๋น๋ฒ์ ๊ตด (๋ฌผ X, ๊ณ ์ด๋์น O)
S: ๊ณ ์ด๋์น ์์น (๋ฌผ O, ๊ณ ์ด๋์น O)
'''
# 9:30 ~
import sys
from collections import deque
r, c = map(int, sys.stdin.readline().split())
visited = [[False] * c for _ in range(r)]
visitedW = [[False] * c for _ in range(r)]
graph = []
S = None # 2) ์ขํ ์ฌ์ฉ ์ ํํ ์ฒ์ ์ ์ธ
D = None
water = deque()
dy = [0, 1, 0, -1]
dx = [1, 0, -1, 0]
for i in range(r):
l = list(map(str, sys.stdin.readline().strip())) # 1) split: ๊ณต๋ฐฑ๊ธฐ์ค / strip: ๋ฌธ์์ด ์์ชฝ ๊ณต๋ฐฑ ์ ๊ฑฐ
for j, s in enumerate(l):
if s == 'S':
S = (i, j)
elif s == 'D':
D = (i, j)
elif s == '*':
water.append((i, j))
graph.append(l)
def water_spread():
global water
size = len(water)
for i in range(size):
wy, wx = water.popleft()
for j in range(4):
ny = wy + dy[j]
nx = wx + dx[j]
if 0 <= ny < r and 0 <= nx < c:
if visitedW[ny][nx] == False:
visitedW[ny][nx] = True
if graph[ny][nx] == ".":
water.append((ny, nx))
graph[ny][nx] = "*"
def bfs():
global r, c, S
is_possible = False
queue = deque()
cnt = 1
queue.append((S[0], S[1], cnt))
last = 0
while queue:
y, x, cnt = queue.popleft()
if last != cnt:
last = cnt
water_spread() # ๋ฌผ ๋จผ์ ํ์ฅ
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if 0 <= ny < r and 0 <= nx < c:
if visited[ny][nx] == False:
visited[ny][nx] = True
if graph[ny][nx] == ".":
queue.append((ny, nx, cnt + 1))
elif graph[ny][nx] == "D":
is_possible = True
print(cnt)
if is_possible == False:
print("KAKTUS")
return
bfs()
๐ก์ฃผ์ ๋ก์ง
1. ๋ฌผ์ ๋จผ์ ์, ํ, ์ข, ์ฐ๋ก ํ์ฅ์ํค๊ธฐ
์ด๋, for๋ฌธ์ ํ์ฌ queue์ ํฌ๊ธฐ๋งํผ ๋๋ค. (ํ์ฌ ์๊ฐ์ ์กด์ฌํ๋ ๋ฌผ์ ๊ฐฏ์๋งํผ)
๋ง์ฝ ๋ค์์ ์ด๋ํ ์นธ์ด ๋น์นธ์ด๋ผ๋ฉด graph์ ์นธ์ด ๋ฌผ์์ ๊ธฐ๋กํด์ค๋ค.
2. ๊ณ ์ด๋์น ์ด๋์ํค๊ธฐ
๋ง์ฝ ๋ค์์ ์ด๋ํ ์นธ์ด ๋น์นธ์ด๋ผ๋ฉด ๊ณ ์ด๋์น๋ฅผ ์ด๋์ํจ๋ค.
๋ง์ฝ ๋ค์์ ์ด๋ํ ์นธ์ด ๋ฌผ์ด๋ผ๋ฉด ๋ฆฌํด์ํค๋ ์ฝ๋๋ ์์ฑํ ํ์๊ฐ ์๋ค.
- ๋ง์ฝ ํ์ฌ ๋ถ์ ๊ณ ์ด๋์น๊ฐ ์, ํ, ์ข, ์ฐ๋ก ์ด๋์ํค๋ ค๋ ์นธ์ด ์ ๋ถ ๋ฌผ์ด๋ผ๋ฉด ๋ฆฌํด์ํค๋ ์ฝ๋๋ ์์ฑํ ํ์๊ฐ ์๋ค.
- ์ด์ฐจํผ, queue์ ์ขํ๋ฅผ ๋ชป๋ฃ์ผ๋ฏ๋ก while queue:๋ฌธ์ด ์ข ๋ฃ๋ ๊ฒ์ด๊ธฐ ๋๋ฌธ์ด๋ค.
๋ํ, ๋งค๋ถ๋ง๋ค ๋ฌผ์ฒ๋ผ ๊ณ ์ด๋์น์ ์ขํ๋ฅผ graph์ ๊ธฐ๋กํ๋ฉฐ ์ด๋์ํฌ ํ์๋ ์๋ค. (pop, add ๋ฑ์ผ๋ก)
์ด๋, ๋ฌผ์ ํ์ฅ์ํค๋ ํจ์๋ฅผ ๋งค๋ฒ ํธ์ถํ์ง ์๊ณ , ๋ถ์ด ์ง๋ฌ์ผ๋ฉด ํ์ฅ์ํจ๋ค.
์ฆ, cnt์ ํตํด ํ์ฌ ๋ถ์ ํ๋จํ ํ ๋ฌผ์ ํ์ฅ์ํค๋ ํจ์๋ ๋งค ๋ถ๋ง๋ค ํ๋ฒ๋ง ํธ์ถํ๋ค.
'Algorithm > Graph' ์นดํ ๊ณ ๋ฆฌ์ ๋ค๋ฅธ ๊ธ
| [ํ๋ก๊ทธ๋๋จธ์ค] ์ฟผ๋ ์์ถ ํ ๊ฐ์ ์ธ๊ธฐ (ํ์ด์ฌ) (0) | 2026.07.12 |
|---|---|
| [ํ๋ก๊ทธ๋๋จธ์ค] Level3 : ์ฌ ์ฐ๊ฒฐํ๊ธฐ (ํ์ด์ฌ) (0) | 2025.10.19 |
| [๋ฐฑ์ค] 2583 : ์์ญ ๊ตฌํ๊ธฐ (ํ์ด์ฌ) (1) | 2025.01.26 |
| ํ๋ก๊ทธ๋๋จธ์ค ๋คํธ์ํฌ (1) | 2025.01.04 |
| [๋ฐฑ์ค] 1647 : ๋์ ๋ถํ ๊ณํ (ํ์ด์ฌ) (3) | 2024.08.14 |