[백준 python] bfs/dfs - 미로 탐색

이혜지·2022년 2월 24일
0

Algorithm

목록 보기
6/12
post-thumbnail

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

거리의 비용이 모두 1이고, 최단 거리를 탐색해야 하기 때문에 BFS로 풀었다.

from collections import deque

n, m = map(int, input().split())

graph = []
for _ in range(n):
    graph.append(list(map(int, input())))
    
dx = [-1, 1, 0, 0]
dy = [0, 0, -1, 1]

def bfs(x, y):
    queue = deque()
    queue.append((x, y))
    
    while queue:
        x, y = queue.popleft()
        
        for i in range(4):
            # 현재 위치에서 네방향으로 위치 확인
            nx = x + dx[i]
            ny = y + dy[i]
            
            if nx < 0 or ny < 0 or nx >= n or ny >= m:
                continue
            #벽이면 무시
            if graph[nx][ny] == 0:
                continue
            
            if graph[nx][ny] == 1:
                graph[nx][ny] = graph[x][y] + 1
                queue.append((nx, ny))
    
    #최단거리 반환
    return graph[n - 1][m - 1]

print(bfs(0,0))
profile
공유 문화를 지향하는 개발자입니다.

0개의 댓글