Python coding

Many distance queries on a small map

A map has n towns numbered 0 to n - 1. Each entry of roads is [a, b, km]: a two-way road of length km. Each entry of queries is [start, end]. Return a list with the length of the shortest route for each query, in order, or -1 when the two towns are not connected. A town is 0 km from itself.

There are at most 100 towns but there can be thousands of queries. Lengths are positive, no road joins a town to itself, and two towns may be joined by several roads.

Besides the tests, one large input (30 towns, 10,000 queries) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

  • shortest_distances(4, [[0,1,4],[1,2,1],[0,2,7],[2,3,2]], [[0,2],[0,3],[3,1],[1,1]]) → [5,7,3,0]
  • shortest_distances(4, [[0,1,3],[2,3,5]], [[0,1],[1,2],[3,2]]) → [3,-1,5]
  • shortest_distances(2, [[0,1,9],[1,0,4]], [[1,0],[0,1]]) → [4,4]
Ctrl/⌘ + Enter runs · Tab indents
Hint 1

Running a search per query repeats the same work thousands of times. With at most 100 towns, an n × n table of every distance is cheap.

Hint 2

Floyd-Warshall: start from the direct roads (keep the shortest of parallel ones), then for each town k try every pair i, j through k.

Hint 3

The loop over k, the town in between, must be the outermost one; i and j go inside it.

Solution and why it works
pythonO(n³ + E + q), E = len(roads), q = len(queries) · O(n²)
def shortest_distances(n: int, roads: list[list[int]], queries: list[list[int]]) -> list[int]:
    INF = float("inf")
    dist = [[0 if i == j else INF for j in range(n)] for i in range(n)]
    for a, b, km in roads:
        if km < dist[a][b]:                  # parallel roads: keep the shortest
            dist[a][b] = dist[b][a] = km
    for k in range(n):                       # now routes may also pass through town k
        row_k = dist[k]
        for row in dist:
            via = row[k]
            for j in range(n):
                if via + row_k[j] < row[j]:
                    row[j] = via + row_k[j]
    return [-1 if dist[a][b] == INF else dist[a][b] for a, b in queries]

After round k, dist[i][j] is the shortest route whose stops in between are all among towns 0..k, so after the last round it is the true distance; each query is then a lookup. Thousands of searches, one per query, redo the same work. Two traps: k must be the outer loop (inside, it reads distances that aren't final yet), and a later, longer parallel road must not overwrite a shorter one.