SDE & MLE Prep

1976. Number of Ways to Arrive at Destination

Problem

roads[i] = [u, v, time] are two-way roads between intersections 0…n − 1. Return how many different routes take the shortest possible time from intersection 0 to n − 1, modulo 10⁹ + 7.

Example: n = 7, roads = [[0,6,7],[0,1,2],[1,2,3],[1,3,3],[6,3,3],[3,5,1],[6,5,1],[2,5,1],[0,4,5],[4,6,2]] → 4

Constraints: n ≤ 200; times up to 10⁹.

Dijkstra while counting shortest paths: a strictly shorter distance to v resets ways[v] = ways[u]; an equal distance adds ways[u].

Complexity: O(E log V).

class Solution:
    def countPaths(self, n: int, roads: List[List[int]]) -> int:
        MOD = 10 ** 9 + 7
        g = defaultdict(list)
        for a, b, t in roads:
            g[a].append((b, t))
            g[b].append((a, t))
        dist, ways = [float("inf")] * n, [0] * n
        dist[0], ways[0] = 0, 1
        pq = [(0, 0)]
        while pq:
            d, u = heappop(pq)
            if d > dist[u]:
                continue
            for v, t in g[u]:
                if d + t < dist[v]:
                    dist[v], ways[v] = d + t, ways[u]
                    heappush(pq, (dist[v], v))
                elif d + t == dist[v]:
                    ways[v] = (ways[v] + ways[u]) % MOD
        return ways[n - 1]