μ²μ μ€κ³λ₯Ό νμ λλ μ΅λ¨κ²½λ‘μ΄λκΉ λ²½ 1κ°λ₯Ό λΆμκ³ κ°λ λͺ¨λ κ²½μ°μ μμ λ²½μ λΆμμ§μκ³ κ°λ λͺ¨λ κ²½μ°μ μλ₯Ό ꡬν΄μ κ°μ₯ μμ κ°μ ꡬν΄μΌνλ€κ³ μκ°νλ€. κ·Έλμ λ°±νΈλνΉμ μκ°νλλ° μκ° μ΄κ³Όμ μ°λ €κ° μμλ€.
β κ·Έλ λ€λ©΄ μ΄λ»κ² μ²λ¦¬ν κΉ?
3μ°¨μ νλ ¬λ‘ ννν΄μ λ²½μ λΆμμ§ μμ κ²½λ‘μμμ κ°μ, λ²½μ λΆμ κ²½λ‘μμμ κ°μλ₯Ό λ°λ‘ μ μ₯νλ€.# index 0 : λ²½μ λΆμμ§ μμ κ²½λ‘μ κ°μ, index 1 : λ²½μ λΆμ κ²½λ‘μ κ°μ
visited = [[[0, 0] for _ in range(m)] for _ in range(n)]
# 3μ°¨μ νλ ¬ (첫 μμ λ
Έλλ λ²½μ λΆμμ§μμ κ²½λ‘μ κ°μ 1 μ€μ )
visited[0][0][0] = 1
bfsλ λ μ§μ μ¬μ΄μ μ΅λ¨ κ²½λ‘λ₯Ό ꡬν΄μ£ΌκΈ° λλ¬Έμ (n-1,m-1) μ’νμ λμ°©νμ λ λ²½μ λΆμ κ²½μ°κ° queueμ **λ¨Όμ ** λ€μ΄μ¨λ€λ©΄, κ·Έ κ²½μ°κ° μ΅λ¨ κ²½λ‘κ° λλ κ²μ΄λ€!μ
λ ₯κ°μ΄ split λμ΄μμ§ μμμ λ¬Έμμ΄ λ¦¬μ€νΈλ‘ λ°κ³ , mapμ μ¬μ©ν΄μ λ€μ intλ‘ λ³ννμλ€.
import sys
from collections import deque
n, m = map(int, sys.stdin.readline().split())
graph = []
for _ in range(n):
raw = list(map(int, list(sys.stdin.readline().rstrip())))
graph.append(raw)
# μ€κ°μ λ²½μ λ¨ νλ²λ§ λΆμ μ μμΌλ―λ‘ λ²½μ λΆμλμ§ μ¬λΆλ₯Ό 3μ°¨μ νλ ¬λ‘ νν
# zκ° 0μ΄λ©΄ λ²½μ νκ΄΄ν μ μκ³ , zκ° 1μ΄λ©΄ λΆκ°λ₯
# λ²½μ λΆμμ§ μμ κ²½λ‘, λ²½μ λΆμ κ²½λ‘
visited = [[[0, 0] for _ in range(m)] for _ in range(n)]
# μ²μ μμ λ
Έλ ν¬ν¨μ΄λ―λ‘ λ²½μ λΆμμ§μμ κ²½λ‘μ κ°μ 1λ‘ μ€μ
visited[0][0][0] = 1
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]
# μ΅λ¨κ²½λ‘ -> bfs
def bfs(x, y, z):
queue = deque([(x, y, 0)])
while queue:
cur_x, cur_y, cnt = queue.popleft()
# λ μ μ λλ¬νλ©΄ μ΄λ νμλ₯Ό μΆλ ₯
if cur_x == n-1 and cur_y == m-1 :
return visited[cur_x][cur_y][cnt]
for i in range(4):
nx, ny = cur_x + dx[i], cur_y + dy[i]
if 0 <= nx < n and 0 <= ny < m:
# λ€μ μ΄λν κ³³μ΄ λ²½μ΄ μλκ³ , μμ§ νλ²λ λ°©λ¬Ένμ§ μμ κ³³μ΄λ©΄
# λ²½ νκ΄΄κΈ°νλ₯Ό νλ² μ¬μ©νλ©΄ κ³μ cntλ 1 (indexκ° 1μΈ κ³³μ κ³μ κ°μ μ μ₯)
if graph[nx][ny] == 0 and visited[nx][ny][cnt] == 0 :
visited[nx][ny][cnt] = visited[cur_x][cur_y][cnt] + 1
queue.append((nx, ny, cnt))
# λ€μ μ΄λν κ³³μ΄ λ²½μ΄κ³ , λ²½ νκ΄΄κΈ°νλ₯Ό μ¬μ©νμ§ μμ κ²½μ°
elif graph[nx][ny] == 1 and cnt == 0 :
# λ²½μ λΆμ κ²½λ‘μ κ°μ μΆκ°
visited[nx][ny][1] = visited[cur_x][cur_y][0] + 1
queue.append((nx, ny, 1))
return -1
print(bfs(0, 0, 0))
# μ°κ΅¬μ λ¬Έμ μ λΉμ·νκ² νμ΄
from collections import deque
import sys
input = sys.stdin.readline
def bfs():
queue = deque()
trial = [item[:] for item in grid]
queue.append([0, 0])
while queue:
if trial[n-1][m-1] != 0:
break
y, x = queue.popleft()
for i in range(4):
ny = y + dy[i]
nx = x + dx[i]
if ny <= -1 or ny >= n or nx <= -1 or nx >= m:
continue
if trial[ny][nx] == 0:
trial[ny][nx] = trial[y][x] + 1
queue.append([ny, nx])
global answer
if trial[n-1][m-1] >= 1:
answer = min(answer, trial[n-1][m-1])
def breakWall():
for i in range(n):
for j in range(m):
if grid[i][j] == 1:
grid[i][j] = 0
bfs()
grid[i][j] = 1
n, m = map(int, input().split())
grid = []
dy = [-1, 1, 0, 0]
dx = [0, 0, -1, 1]
for _ in range(n):
grid.append(list(map(int, input().strip())))
answer = float("inf")
bfs()
breakWall()
if n == 1 and m == 1:
print(1)
elif answer == float("inf"):
print(-1)
else:
print(answer+1)