프로그래밍/Python

백준_python 2178번 미로 탐색(그래프, BFS)

O'bin 2024. 4. 21. 15:28

<문제 링크>

https://www.acmicpc.net/problem/2178

 

2178번: 미로 탐색

첫째 줄에 두 정수 N, M(2 ≤ N, M ≤ 100)이 주어진다. 다음 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
from collections import deque
 
n, m = map(int, input().split())
maze = [list(map(int, input())) for _ in range(n)]
 
 
def bfs(graph, x, y):
    q = deque([(00)])
    
    # 상하좌우 이동 값
    dx = [-1100]        
    dy = [00-11]
 
 
    while q:
        x, y = q.popleft()
 
        for i in range(4):
            nx, ny = x + dx[i], y + dy[i]
            
            if 0 <= nx < n and 0 <= ny < m and graph[nx][ny] == 1:
                q.append((nx, ny))
                graph[nx][ny] = graph[x][y] + 1
 
    return graph[n-1][m-1]
 
print(bfs(maze, 00))
cs

 

현재 위치에서 상하좌우 중 움직일 수 있는 방향의 값에 +1을 해서

특정 위치에 도달하려면 몇번 이동해야하는지를 구한다

 

 

마지막 graph 상태