https://www.acmicpc.net/problem/2665
import sys
from collections import deque
input = sys.stdin.readline
dx = [0, 0, -1, 1]
dy = [-1, 1, 0, 0]
n = int(input())
visited = [[-1 for _ in range(n)] for _ in range(n)]
room = []
for _ in range(n):
room.append(list(input().rstrip('\n')))
que = deque()
x, y = 0, 0
que.append((x, y))
visited[0][0] = 0
while que:
x, y = que.popleft()
if x == n-1 and y == n-1:
print(visited[n-1][n-1])
break
for i in range(4):
nx = x+dx[i]
ny = y + dy[i]
if 0 <= nx < n and 0 <= ny < n and visited[nx][ny] == -1:
if room[nx][ny] == '1':
visited[nx][ny] = visited[x][y]
que.appendleft((nx, ny))
elif room[nx][ny] == '0':
visited[nx][ny] = visited[x][y]+1
que.append((nx, ny))