ํ์ด
[0][0]
์์ [n-1][m-1]
์ขํ๊น์ง์ ์ต๋จ๊ฑฐ๋ฆฌ ๋ฌธ์ ์ด๊ธฐ ๋๋ฌธ์ BFS ๋ฅผ ํ์ฉํ๋ค.
์ด์ ๊ธฐ๋ณธ์ ์ธ BFS ๊ตฌ์กฐ๋ ์ดํดํ๊ณ ๋ค์ํ ๋ฐฉ๋ฉด์์ ํ์ฉํ ์ ์๋ค.
โ์๊ธฐ์์ดโ ๋ฌธ์ ์์ ํ์ฉํ๋ dist ๋ฐฐ์ด์ ํตํด ๋ฏธ๋ก๋ฅผ ํ์ํ๋ฉด์ ๊ฐ ์ขํ๋ณ ์์์ ๋ถํฐ์ ๊ฑฐ๋ฆฌ๋ฅผ ์ ์ฅํ๋๋ก ์ฝ๋๋ฅผ ์์ฑํ๋ค.
์์์ ์์ BFS ๋ฅผ ์คํ์์ผ ๋ชจ๋ ํ์์ด ๋๋ ํ dist[n-1][m-1]
์ ๋ฐํํ์ฌ ์ต๋จ๊ฑฐ๋ฆฌ๋ฅผ ๊ณ์ฐํ ์ ์๋ค.
์์ค์ฝ๋
# ๋ฏธ๋ก ํ์
from collections import deque
import sys
input = sys.stdin.readline
def bfs(i, j):
q = deque()
q.append([i, j])
graph[i][j] = 0 # ์์ ์ ๋ฐฉ๋ฌธ์ฒ๋ฆฌ
dist[i][j] = 1
while q:
x, y = q.popleft()
for k in range(4):
nx = x + dx[k]
ny = y + dy[k]
if 0 <= nx < n and 0 <= ny < m: # ๋ฒ์ ๋ด์ผ ๋
if graph[nx][ny] == 1: # ํต๋ก์ผ ๊ฒฝ์ฐ
q.append([nx, ny])
graph[nx][ny] = 0 # ๋ฐฉ๋ฌธ ์ฒ๋ฆฌ
dist[nx][ny] = dist[x][y] + 1 # ์ขํ๋ณ ๊ฑฐ๋ฆฌ ์ ์ฅ
return dist[n-1][m-1]
dx = [1, -1, 0, 0]
dy = [0, 0, -1, 1]
n, m = map(int, input().split())
graph = [list(map(int, input().rstrip())) for _ in range(n)]
dist = [[0] * m for _ in range(n)]
print(bfs(0, 0))