본문 바로가기

백준 코딩 테스트

다익스트라 알고리즘 - 배열에 cost가 주어질 시 탬플릿 코드

728x90
import heapq
import sys

input = sys.stdin.readline

cnt = 1
INF = int(1e9)

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

def dijkstra():
    q = []
    heapq.heappush(q, (graph[0][0], 0, 0))
    distance[0][0] = 0

    while q:
        cost, x, y = heapq.heappop(q)

        if x == n - 1 and y == n - 1:
            print(f'Problem {cnt}: {distance[x][y]}')
            break

        for i in range(4):
            nx = x + dx[i]
            ny = y + dy[i]

            if 0 <= nx < n and 0 <= ny < n:
                newCost = cost + graph[nx][ny]

                if newCost < distance[nx][ny]:
                    distance[nx][ny] = newCost
                    heapq.heappush(q, (newCost, nx, ny))

while True:
    n = int(input())
    if n == 0:
        break

    graph = [list(map(int, input().split())) for _ in range(n)]
    distance = [[INF] * n for _ in range(n)]

    dijkstra()
    cnt += 1
728x90

'백준 코딩 테스트' 카테고리의 다른 글

다익스트라 템플릿  (0) 2023.12.15
[백준] 백준 풀 문제 정리  (0) 2023.07.10
백준 2143 - 두배열의 합  (0) 2021.04.19
백준 2632번 - 피자판매  (0) 2021.04.19
백준 7453번 - 합이 0인 네 정수  (0) 2021.04.19