Python coding

Count the fastest routes

A town has n intersections numbered 0 to n - 1. Each entry of roads is [u, v, minutes]: a two-way road between u and v that takes minutes to drive. Return how many different routes from intersection 0 to intersection n - 1 take the least possible time; two routes differ if their sequences of intersections differ. Return 0 if n - 1 cannot be reached; when n == 1, staying put counts as one route.

Every road takes at least 1 minute, no road joins an intersection to itself, and no two roads join the same pair.

Besides the tests, one large input (61 intersections, 1,048,576 fastest routes) with a ~100 ms limit (scaled to your device's speed): brute force won't pass.

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

Run Dijkstra from 0, and next to each distance keep ways[v]: how many fastest routes reach v so far.

Hint 2

Relaxing u → v: a strictly faster time replaces ways[v] with ways[u]; an equal time adds ways[u] to it. With positive weights, ways[u] is final when u is popped.

Solution and why it works
pythonO((n + E) log n), E = len(roads) · O(n + E)
import heapq


def count_fastest_routes(n: int, roads: list[list[int]]) -> int:
    adj = [[] for _ in range(n)]
    for u, v, w in roads:
        adj[u].append((v, w))
        adj[v].append((u, w))
    dist, ways = [float("inf")] * n, [0] * n
    dist[0], ways[0] = 0, 1
    heap = [(0, 0)]
    while heap:
        d, u = heapq.heappop(heap)
        if d > dist[u]:
            continue                             # stale entry
        for v, w in adj[u]:
            if d + w < dist[v]:                  # faster: forget the slower routes
                dist[v], ways[v] = d + w, ways[u]
                heapq.heappush(heap, (d + w, v))
            elif d + w == dist[v]:               # a tie: every fastest route to u extends
                ways[v] += ways[u]
    return ways[n - 1]

Every fastest route to v ends with a road u → v where dist[u] + w == dist[v], so ways[v] is the sum of ways[u] over those roads. Dijkstra pops intersections in order of time and every road takes at least a minute, so each such u is popped, with its count final, before v. A faster arrival resets the count; a tie adds to it. Traps: adding on a faster arrival instead of resetting, and listing every route, which grows exponentially.