<이것이 취업을 위한 코딩테스트다>를 공부하며 정리한 내용입니다.
5 6
101010
111111
000001
111111
111111
10
from collections import deque
n,m=map(int,input().split())
miro=[]
for i in range(n):
miro.append(list(map(int, input())))
wh=[(1,0),(0,1),(0,-1),(-1,0)]
#가장 가까운 곳부터 살펴야하니까 BFS로...해보자고 ....
def bfs(start):
go=deque([start]) #방문할 곳 큐에 저장. 가장 처음은 시작점
while go: #큐가 비어있을 때까지 해야할까 아님 위치가 n.m일때로 해야할까.
x,y=go.popleft()
for i in wh:
x0=x+i[0]
y0=y+i[1]
#만약 범위에서 넘어가면 이 위치는 아웃
if x0<0 or x0>=n or y0<0 or y0>=m:
continue
#괴물이 있는 곳이라면
if miro[x0][y0]==0:
continue
#괴물이 없는 처음 가보는 곳이라면
if miro[x0][y0]==1:
miro[x0][y0]=miro[x][y]+1 #최단 거리 기록하기
go.append((x0,y0)) #방문할 곳에 추가
return miro[n-1][m-1]
print(bfs((0,0)))