https://www.acmicpc.net/problem/1261
import sys
from collections import deque
input = sys.stdin.readline
dx = [1, 0, -1, 0]
dy = [0, 1, 0, -1]
graph = []
def bfs():
que = deque()
x, y = 0, 0
que.append((x, y))
visited[x][y] = 0
while que:
x, y = que.popleft()
for i in range(4):
nx = x + dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < m and visited[nx][ny] == -1:
if graph[nx][ny] == '0':
visited[nx][ny] = visited[x][y]
que.appendleft((nx, ny))
elif graph[nx][ny] == '1':
visited[nx][ny] = visited[x][y] + 1
que.append((nx, ny))
m, n = map(int, input().split())
visited = [[-1 for _ in range(m)]for _ in range(n)]
for _ in range(n):
temp = list(input().rstrip('\n'))
graph.append(temp)
bfs()
print(visited[n-1][m-1])
백준 2665번과 유사하다.