1+ from collections import deque
2+
3+ # 입력 받기
4+ N , M = map (int , input ().split ())
5+ maps = []
6+ for _ in range (N ):
7+ temp = input ().strip ()
8+ maps .append (list (map (int , temp )))
9+
10+ # 방문 배열 초기화
11+ visited = [[[0 ] * 2 for _ in range (M )] for _ in range (N )]
12+ visited [0 ][0 ][0 ] = 1
13+ # visited[x][y][0] = 벽을 뚫지 않고 온 최단 경로
14+ # visited[x][y][1] = 벽을 1회 뚫고 온 최단 경로
15+
16+ # BFS 탐색 방향 (상, 우, 하, 좌)
17+ directions = [(- 1 , 0 ), (0 , 1 ), (1 , 0 ), (0 , - 1 )]
18+
19+ # BFS 큐 초기화
20+ queue = deque ([(0 , 0 , 0 )])
21+
22+ # BFS 시작
23+ while queue :
24+ x , y , wall = queue .popleft ()
25+
26+ # 목표 지점 도달 시 최단 거리 출력
27+ if x == N - 1 and y == M - 1 : # 목표지점에 도달했다면
28+ print (visited [x ][y ][wall ])
29+ exit (0 )
30+
31+ # 네 방향 탐색
32+ for dx , dy in directions :
33+ nx , ny = x + dx , y + dy
34+
35+ # 맵 범위를 벗어난 경우 무시
36+ if nx < 0 or nx >= N or ny < 0 or ny >= M :
37+ continue
38+
39+ # 벽이고 벽 파괴를 아직 안 쓴 경우, 벽 부수기 가능. 값을 업데이트하고 큐에 추가
40+ if maps [nx ][ny ] == 1 and wall == 0 :
41+ visited [nx ][ny ][1 ] = visited [x ][y ][0 ] + 1
42+ queue .append ((nx , ny , 1 ))
43+ # 벽이 아니고, 아직 방문하지 않았을 경우에는 이동 가능하므로 큐에 추가
44+ elif maps [nx ][ny ] == 0 and visited [nx ][ny ][wall ] == 0 :
45+ visited [nx ][ny ][wall ] = visited [x ][y ][wall ] + 1
46+ queue .append ((nx , ny , wall ))
47+
48+ # 도달하지 못한 경우 -1 출력
49+ print (- 1 )
0 commit comments