문제출처 : acmicpc.net/problem/2178
입력을 받고 check를 만들어준다.
check는 방문햇는지 안했는지와 얼마나 거쳐서 왔는지를 표현해준다.
인접한 board요소들을 방문하며 check에 표시해준다.
리스트 인덱스 에러에 주의하자.
import sys
from collections import deque
input = sys.stdin.readline
y,x = map(int,input().split())
board = [list(input()[:-1]) for i in range(y)]
check = [[0]*x for i in range(y)]
q=deque()
q.append([0,0])
check[0][0] = 1
dx = [1,-1,0,0]
dy = [0,0,1,-1]
while q:
b,a = q.popleft()
for i in range(4):
_y = b + dy[i] if 0<= b+dy[i] < y else b
_x = a + dx[i] if 0 <= a + dx[i] < x else a
if check[_y][_x] == 0 and board[_y][_x] == "1":
check[_y][_x] = check[b][a] + 1
q.append([_y,_x])
print(check[y-1][x-1])