Graph Theory37 sections · 1633 units
Open in Course

CSES 1671 Shortest Routes I - Implementation

(C++ code)

Standard Dijkstra implementation:

dist = array of size n + 1, all infinity
dist[1] = 0
pq = min-heap with (0, 1)

while pq is not empty:
    (d, u) = pq.pop()
    if d > dist[u]:
        continue
    for (v, w) in adj[u]:
        if dist[u] + w < dist[v]:
            dist[v] = dist[u] + w
            pq.push((dist[v], v))

for i from 1 to n:
    print dist[i]

If a node is unreachable, dist[i] remains infinity.