Notice
Recent Posts
Recent Comments
Link
«   2024/09   »
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
Archives
Today
Total
관리 메뉴

Life Engineering

[BOJ 2206] 벽 부수고 이동하기 (Python3) 본문

Problem Solving

[BOJ 2206] 벽 부수고 이동하기 (Python3)

흑개 2021. 2. 20. 17:55

www.acmicpc.net/problem/2206

 

2206번: 벽 부수고 이동하기

N×M의 행렬로 표현되는 맵이 있다. 맵에서 0은 이동할 수 있는 곳을 나타내고, 1은 이동할 수 없는 벽이 있는 곳을 나타낸다. 당신은 (1, 1)에서 (N, M)의 위치까지 이동하려 하는데, 이때 최단 경로

www.acmicpc.net

 

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,0for _ 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>=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 값을 리턴한다.