Skip to content

Commit fcef8d3

Browse files
committed
[BOJ] #2206.벽 부수고 이동하기 / 골드3 / 70(X)
1 parent 524ec79 commit fcef8d3

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
from collections import deque
2+
3+
N, M = map(int, input().split())
4+
graph = [list(map(int, input())) for _ in range(N)]
5+
6+
# 상하좌우 방향 정의
7+
directions = [(-1,0), (0,1), (1,0), (0,-1)]
8+
9+
# BFS
10+
def bfs():
11+
# 3차원 방문 배열: visited[x][y][벽 부숨 여부]
12+
# wall=0: 벽을 부수지 않고 도달한 경우
13+
# wall=1: 벽을 한번 부수고 도달한 경우
14+
visited = [[[0] * 2 for _ in range(M)] for _ in range(N)]
15+
queue = deque([(0,0,0)]) # (x, y, 벽 부순 여부)
16+
visited[0][0][0] = 1 # 시작점 방문처리 (벽을 부수지 않고)
17+
18+
while queue:
19+
x, y, wall = queue.popleft()
20+
21+
# 도착지에 도달한 경우 거리 반환
22+
if x == N-1 and y == M-1:
23+
return visited[x][y][wall]
24+
25+
# 4가지 방향 탐색
26+
for dx, dy in directions:
27+
nx, ny = x + dx, y + dy
28+
29+
# 맵 범위 안에 있는 경우만 처리
30+
if 0 <= nx < N and 0 <= ny < M:
31+
# 이동하려는 칸이 빈칸(0)이고, 방문하지 않은 경우
32+
if graph[nx][ny] == 0 and visited[nx][ny][wall] == 0:
33+
visited[nx][ny][wall] = visited[x][y][wall] + 1
34+
queue.append((nx, ny, wall))
35+
36+
# 이동하려는 칸이 벽(1)이고, 아직 벽을 부순 적이 없는 경우
37+
if graph[nx][ny] == 1 and wall == 0 and visited[nx][ny][1] == 0:
38+
visited[nx][ny][1] = visited[x][y][wall] + 1
39+
queue.append((nx, ny, 1))
40+
41+
# BFS 종료 후에도 도달하지 못한 경우
42+
return -1
43+
44+
print(bfs())

0 commit comments

Comments
 (0)