[백준] 1753번 최단경로

거북이·2023년 8월 24일
0

백준[골드4]

목록 보기
37/59
post-thumbnail

💡문제접근

  • 데이크스트라 알고리즘 기초 문제

💡코드(메모리 : 68528KB, 시간 : 652ms)

import heapq
import sys
input = sys.stdin.readline
INF = int(1e9)

V, E = map(int, input().strip().split())
K = int(input())                            # 시작 노드의 번호
graph = [[] for _ in range(V+1)]
distance = [INF] * (V+1)

for _ in range(E):
    # u에서 v로 가는 가중치 w인 간선이 존재한다
    u, v, w = map(int, input().strip().split())
    graph[u].append((v, w))

def dijkstra(start):
    q = []
    heapq.heappush(q, (0, start))
    distance[start] = 0
    while q:
        dist, now = heapq.heappop(q)
        # 가중치를 갱신할 필요가 없는 경우
        if distance[now] < dist:
            continue
        for i in graph[now]:
            cost = dist + i[1]
            if cost < distance[i[0]]:
                distance[i[0]] = cost
                heapq.heappush(q, (cost, i[0]))

dijkstra(K)

for i in range(1, V+1):
    if distance[i] == INF:
        print("INF")
    else:
        print(distance[i])

💡소요시간 : 50m

0개의 댓글