본문 바로가기
알고리즘/백준

백준-2178번(미로 탐색)-python3

by nyeongha 2023. 11. 24.
from collections import deque

N, M = map(int, input().split())

graph = []

for _ in range(N):
  graph.append(list(map(int, input())))

# 너비 우선 탐색
def bfs(x, y):
    # 이동할 네 가지 방향 정의 (상, 하, 좌, 우)
    dx = [-1, 1, 0, 0] 
    dy = [0, 0, -1, 1]

    q=deque()
    q.append((x,y))

    while q:
        # print(q)
        x,y=q.popleft()
        for i in range(4):
            nx=x+dx[i]
            ny=y+dy[i]

            if (nx<0) or (ny<0) or (nx>N-1) or (ny>M-1):
                continue

            if graph[nx][ny]==0:
                continue

            elif graph[nx][ny]==1:
                graph[nx][ny]=graph[x][y]+1
                # for j in graph:
                #     print(*j,end='\n')
                q.append((nx,ny))

    return graph[N-1][M-1]

print(bfs(0, 0))

'알고리즘 > 백준' 카테고리의 다른 글

백준-2292번(벌집)-python3  (0) 2023.11.24
백준-2231번(분해합)-python3  (0) 2023.11.24
백준-2164번(카드2)-python3  (0) 2023.11.24
백준-2163번(초콜릿 자르기)-python3  (0) 2023.11.24
백준-2108번(통계학)-python3  (0) 2023.11.24