Number of Ways to Arrive at Destination

Pattern: Shortest paths

medium

Count the shortest routes from 0 to n - 1. Run Dijkstra and keep, for each vertex, how many shortest routes reach it: on a strictly shorter distance, copy the count; on an equal distance, add it.

The problem

Given n intersections and two-way roads [u, v, time], return the number of ways to travel from 0 to n - 1 in the shortest possible time, modulo 10⁹ + 7.

Think first

  • What does Dijkstra know when it finds a strictly shorter route?
  • And an equally short one?
  • Why must counts be added in distance order?

Hints

    Brute force, and why it fails

    List every shortest route: can be exponential.

    The key insight

    Counts follow Dijkstra's order, so each vertex's count is complete before it is used.

    Dry run

    dist(6)7

    The LeetCode example with 7 intersections. The shortest time to 6 is 7.

    Step 1 of 3

    The plan

    dist, ways; on d < dist[v]: dist[v] = d; ways[v] = ways[u]; push
    on d == dist[v]: ways[v] += ways[u]
    

    Complexity

    Time
    O(E log V)
    Space
    O(V + E)

    Dijkstra plus constant work per edge.

    Edge cases

    • One intersection: 1.
    • Many equal routes: use the modulo.
    • A single road.
    I've built my logic, show the code

    Java

    import java.util.*;
    
    class Solution {
        public int countPaths(int n, int[][] roads) {
            final long MOD = 1_000_000_007L;
            List<List<int[]>> adj = new ArrayList<>();
            for (int i = 0; i < n; i++) adj.add(new ArrayList<>());
            for (int[] r : roads) { adj.get(r[0]).add(new int[]{r[1], r[2]}); adj.get(r[1]).add(new int[]{r[0], r[2]}); }
            long[] dist = new long[n], ways = new long[n];
            Arrays.fill(dist, Long.MAX_VALUE);
            dist[0] = 0;
            ways[0] = 1;
            PriorityQueue<long[]> pq = new PriorityQueue<>((a, b) -> Long.compare(a[0], b[0]));
            pq.add(new long[]{0, 0});
            while (!pq.isEmpty()) {
                long[] top = pq.poll();
                int u = (int) top[1];
                if (top[0] > dist[u]) continue;
                for (int[] e : adj.get(u)) {
                    long d = dist[u] + e[1];
                    if (d < dist[e[0]]) {           // a strictly shorter way: start counting again
                        dist[e[0]] = d;
                        ways[e[0]] = ways[u];
                        pq.add(new long[]{d, e[0]});
                    } else if (d == dist[e[0]]) {   // another shortest way: add its count
                        ways[e[0]] = (ways[e[0]] + ways[u]) % MOD;
                    }
                }
            }
            return (int) (ways[n - 1] % MOD);
        }
    }

    C++

    class Solution {
    public:
        int countPaths(int n, vector<vector<int>>& roads) {
            const long long MOD = 1000000007LL;
            vector<vector<pair<int, int>>> adj(n);
            for (const vector<int>& r : roads) { adj[r[0]].push_back(make_pair(r[1], r[2])); adj[r[1]].push_back(make_pair(r[0], r[2])); }
            vector<long long> dist(n, LLONG_MAX), ways(n, 0);
            dist[0] = 0;
            ways[0] = 1;
            priority_queue<pair<long long, int>, vector<pair<long long, int>>, greater<pair<long long, int>>> pq;
            pq.push(make_pair(0LL, 0));
            while (!pq.empty()) {
                pair<long long, int> top = pq.top();
                pq.pop();
                int u = top.second;
                if (top.first > dist[u]) continue;
                for (const pair<int, int>& e : adj[u]) {
                    long long d = dist[u] + e.second;
                    if (d < dist[e.first]) {        // a strictly shorter way: start counting again
                        dist[e.first] = d;
                        ways[e.first] = ways[u];
                        pq.push(make_pair(d, e.first));
                    } else if (d == dist[e.first]) {   // another shortest way: add its count
                        ways[e.first] = (ways[e.first] + ways[u]) % MOD;
                    }
                }
            }
            return static_cast<int>(ways[n - 1] % MOD);
        }
    };

    Python

    import heapq
    
    class Solution:
        def countPaths(self, n: int, roads: list[list[int]]) -> int:
            MOD = 1_000_000_007
            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
            pq = [(0, 0)]
            while pq:
                d, u = heapq.heappop(pq)
                if d > dist[u]:
                    continue
                for v, w in adj[u]:
                    if d + w < dist[v]:             # a strictly shorter way: start counting again
                        dist[v], ways[v] = d + w, ways[u]
                        heapq.heappush(pq, (dist[v], v))
                    elif d + w == dist[v]:          # another shortest way: add its count
                        ways[v] = (ways[v] + ways[u]) % MOD
            return ways[n - 1] % MOD

    Common mistakes

    • Adding counts on longer routes.
    • Overflow without the modulo.

    Similar problems