Life Engineering
[BOJ 2206] 벽 부수고 이동하기 (Python3) 본문
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
|
from collections import deque
N, M=map(int, input().split())
graph=[]
dist=[[[0,0] for _ in range(M)] for _ in range(N)]
dx=[-1,1,0,0]
dy=[0,0,-1,1]
for i in range(N):
graph.append(list(map(int, input())))
def bfs(x,y,flag):
queue=deque()
queue.append((x,y,flag))
dist[x][y][flag]=1
while queue:
x,y,flag=queue.popleft()
if x==N-1 and y==M-1:
return dist[N-1][M-1][flag]
for i in range(4):
nx=x+dx[i]
ny=y+dy[i]
if nx<0 or nx>=N or ny<0 or ny>=M:
continue
if dist[nx][ny][flag]!=0:
continue
if graph[nx][ny]==0:
dist[nx][ny][flag]=dist[x][y][flag]+1
queue.append((nx,ny,flag))
if graph[nx][ny]==1 and flag==0:
dist[nx][ny][1]=dist[x][y][flag]+1
queue.append((nx,ny,1))
return -1
print(bfs(0,0,0))
|
cs |
역.쉬 골드4 ^0^ 나에겐 너무 버겁다고욧!
그래서 구.글.신을 참조했다~~
해답은 의외로 간단했다.
flag값을 사용하기 위해 3차원 배열을 만든다.
(0,0) 부터 bfs로 탐색 후 방문하지 않은 길(0)이 있으면 dist 배열+1 한다. 방문하지 않은 벽을 만났고, flag값이 0(한번도 벽을 깬 적 없으면) flag 를 1로 바꿔주고 큐에 (nx, ny, 1) 을 넣어 한번 벽을 깼음을 나타낸다.
큐에서 목표 지점을 만나면 해당 인덱스의 dist 값을 리턴한다.
'Problem Solving' 카테고리의 다른 글
[BOJ 9012] 괄호 (Python3) (0) | 2021.02.20 |
---|---|
[BOJ 5014] 스타트링크 (Python3) (0) | 2021.02.20 |
[BOJ 2805] 나무 자르기(Python3) (0) | 2021.02.19 |
[BOJ 1389] 케빈 베이컨의 6단계 법칙 (Python3) (0) | 2021.02.19 |
[BOJ 1931] 회의실 배정 (Python 3) (0) | 2021.02.18 |