Graph Theory37 sections · 1633 units
Open in Course

CSES 1672 Shortest Routes II - Implementation

(Using adjacency matrix)

Here is the solution:

INF = 10^18
dist = 2D array of size (n+1) x (n+1), all INF
for i from 1 to n:
    dist[i][i] = 0

for each edge (a, b, w):
    dist[a][b] = min(dist[a][b], w)
    dist[b][a] = min(dist[b][a], w)

for k from 1 to n:
    for i from 1 to n:
        for j from 1 to n:
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

for each query (a, b):
    if dist[a][b] >= INF:
        print -1
    else:
        print dist[a][b]

Use a large constant like 101810^{18} for infinity to avoid overflow when adding.

This runs in O(n3)O(n^3) time and uses O(n2)O(n^2) space.