[백준] 2178번 미로 탐색

게으른 완벽주의자·2023년 2월 14일

백준

목록 보기
5/27

백준_2178

가장 기본적인 최단거리 구하기 w BFS

from collections import deque
n, m = map(int, input().split())
graph = [list(map(int, input().rstrip())) for _ in range(n)]
visited = [[0]*m for _ in range(n)]

dx = [0,0,1,-1]
dy = [1,-1,0,0]

q = deque()
q.append((0,0))
visited[0][0] = 1
while q:
    x, y = q.popleft()
    for k in range(4):
        nx = x+dx[k]
        ny = y+dy[k]
        if 0<=nx<n and 0<=ny<m:
            if not visited[nx][ny] and graph[nx][ny]==1:
                visited[nx][ny] = 1
                graph[nx][ny] = graph[x][y]+1
                q.append((nx,ny))

print(graph[n-1][m-1])
profile
데이터를 공부하고 있습니다

0개의 댓글