DFS/BFS
λ€μ― λ²μ§Έ λ¬Έμ !
μ€λμ κ΅°λ λΉ‘μΌ λ ,,, 23μμ λΈλ‘κ·Έ κΈ μ°λκΉ μ μ μ μ΄ μλλ€.
# return -1 == λ²μ μ΄κ³Ό || 1 == λμ°© || 0 ==
def dfs(x, y, cnt):
if x < 0 or x >= N or y < 0 or y >= M:
return -1
elif x == N-1 and y == M-1:
result.append(cnt)
return -1
flag = 0
if graph[x][y] == 1:
graph[x][y] = 0
# for j in graph:
# print(j)
# print(x, y, cnt)
flag += dfs(x+1, y, cnt+1)
flag += dfs(x, y+1, cnt+1)
flag += dfs(x-1, y, cnt+1)
flag += dfs(x, y-1, cnt+1)
if flag:
graph[x][y] = 1
return True
return 0
N, M = map(int, input().split())
graph, result = [], []
for _ in range(N):
graph.append(list(map(int, input())))
dfs(0, 0, 1)
print(min(result))
λ μ΅μν dfs
λ‘ νμλλ°,,, λ°νμμλ¬
κ° λ΄λ€.
μ
μΆλ ₯ μμκ° μ μΆλ ₯λμ κ·Έλ₯ λ£μλλ°, μμλ μ€λ₯κ° λ§μλ€.
λ΄ μκ°μ λ¬Έμ λ, μ¬κ· ν¨μμ μ€ν μμλ₯Ό μ λͺ¨λ₯Έ μ±λ‘ μ½λλ₯Ό λ§ μ§°κΈ° λλ¬Έμ΄λ€.
μ무νΌ, κ²μν΄λ³΄λ dfs
λ μ΅λ¨ 거리 λ¬Έμ μ λΆλ¦¬νλ€κ³ λμμμ΄μ λ€μ μ½λλ bfs
λ‘ μμ±νλ€.
from collections import deque
def bfs(x, y):
queue = deque()
queue.append((x, y))
while queue:
# x, y, num μ νμ¬ λ°μ΄ν° μ μ₯
x, y = queue.popleft()
num = graph[x][y]
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
# μ ν μ’ μ° λ
Έλ κ²μ¬
if nx < 0 or nx >= N or ny < 0 or ny >= M:
continue
# 1 μ΄λ©΄, queueμ λ£μ
# νμ¬ λ
Έλμ μ΄μ λ
Έλ κ°μ λνκΈ°
if graph[nx][ny] == 1:
graph[nx][ny] += num
queue.append((nx, ny))
return graph[N-1][M-1]
N, M = map(int, input().split())
graph = []
for _ in range(N):
graph.append(list(map(int, input())))
# μ ν μ’ μ°
dx = [-1, 1, 0 ,0]
dy = [0, 0, -1, 1]
print(bfs(0, 0))
μ΄λ²μ bfs
λ‘ μμ±νλ€.
μ¬λ¬ λΈλ‘κ·Έμ μμμ μ°Έκ³ ν΄μ μμ±νμ§λ§, κ·Έλλ λλ¦ λ§μ΄ κ³ λ―Όνλ€.
μνμ’μ°μ κ΄λ ¨λ λΆλΆμ κ°κ²°νκ² μ§κΈ° μν΄ λλλΉ μ νλΈλ₯Ό μ°Έκ³ νλ€. κ·Όλ° κ²°κ΅ μ½λλ κ±°μ μ μ¬νλ€.
[μκ³ λ¦¬μ¦] κΉμ΄ μ°μ νμ(DFS) κ³Ό λλΉ μ°μ νμ(BFS)
https://devuna.tistory.com/32 [νλ κ°λ°μΌκΈ°π]
(μ΄μ½ν
2021 κ°μ λͺ°μ보기) 3. DFS & BFS
https://www.youtube.com/watch?v=7C9RgOcvkvo