-
Notifications
You must be signed in to change notification settings - Fork 0
/
2178) 미로 탐색.py
45 lines (34 loc) · 1.07 KB
/
2178) 미로 탐색.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
import sys
from collections import deque
def bfs(r,c):
global dist
q = deque()
dist[r][c] = 1
q.append((r,c))
while q:
front = q[0]
row = front[0]
col = front[1]
q.popleft()
for i in range(4):
nextrow = row + drow[i]
nextcol = col + dcol[i]
if nextrow >= H or nextcol >= W or nextrow < 0 or nextcol <0: continue
if dist[nextrow][nextcol] == 0 and maze[nextrow][nextcol] == 1:
dist[nextrow][nextcol] = dist[row][col] + 1
# 상하좌우로 한칸씩 간 곳의 dist는 전부 같아야 함
q.append((nextrow,nextcol))
return dist[H-1][W-1]
dcol = (1, 0, -1, 0)
drow = (0, 1, 0, -1)
H, W = map(int, sys.stdin.readline().split())
maze = [[] for _ in range(H)]
dist = [[0]*W for _ in range(H)]
shortest = 0
for i in range(H):
maze[i] = list(map(int, list(sys.stdin.readline()[:-1])))
for i in range(H):
for j in range(W):
if dist[i][j] == 0 and maze[i][j] == 1:
shortest = bfs(i,j)
print(shortest)