Skip to main content
Back to problems
#1976
Medium Algorithms

Number of ways to arrive at destination

Dynamic Programming Graph Theory Topological Sort Shortest Path
37.3% acceptance
Feb 25, 2026
3849
225
You are in a city that consists of n intersections numbered from 0 to n - 1 with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer n and a 2D integer array roads where roads[i] = [ui, vi, timei] means that there is a road between intersections ui and vi that takes timei minutes to travel. You want to know in how many ways you can travel from intersection 0 to intersection n - 1 in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo 109 + 7.

Solution

Rust
Time O(n * m)
Space O(n * m)
LeetCode
solution.rs
impl Solution {
  pub fn count_paths(n: i32, roads: Vec<Vec<i32>>) -> i32 {
    use std::collections::BinaryHeap;
    use std::cmp::Reverse;
    
    const MOD: i64 = 1_000_000_007;
    let n = n as usize;
    let mut adj = vec![vec![]; n];
    for road in &roads {
      let u = road[0] as usize;
      let v = road[1] as usize;
      let t = road[2] as i64;
      adj[u].push((v, t));
      adj[v].push((u, t));
    }
    
    let mut dist = vec![i64::MAX; n];
    let mut ways = vec![0i64; n];
    dist[0] = 0;
    ways[0] = 1;
    
    let mut heap = BinaryHeap::new();
    heap.push(Reverse((0i64, 0usize)));
    
    while let Some(Reverse((d, u))) = heap.pop() {
      if d > dist[u] {
        continue;
      }
      for &(v, t) in &adj[u] {
        let new_dist = d + t;
        if new_dist < dist[v] {
          dist[v] = new_dist;
          ways[v] = ways[u];
          heap.push(Reverse((new_dist, v)));
        } else if new_dist == dist[v] {
          ways[v] = (ways[v] + ways[u]) % MOD;
        }
      }
    }
    
    ways[n - 1] as i32
  }
}