Number of Ways to Arrive at Destination - Problem

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.

Input & Output

Example 1 — Basic Graph
$ Input: n = 4, roads = [[0,1,1],[0,2,3],[1,3,2],[2,3,1]]
Output: 1
💡 Note: There are two paths from 0 to 3: 0→1→3 (time 3) and 0→2→3 (time 4). Only one path has the shortest time of 3.
Example 2 — Multiple Shortest Paths
$ Input: n = 3, roads = [[0,1,1],[0,2,1],[1,2,1]]
Output: 1
💡 Note: The shortest path from 0 to 2 is the direct path 0→2 with time 1. The path 0→1→2 has time 2, which is longer.
Example 3 — Single Path
$ Input: n = 2, roads = [[0,1,5]]
Output: 1
💡 Note: Only one path from 0 to 1 with time 5, so count is 1.

Constraints

  • 1 ≤ n ≤ 200
  • n - 1 ≤ roads.length ≤ n * (n - 1) / 2
  • roads[i].length == 3
  • 0 ≤ ui, vi ≤ n - 1
  • 1 ≤ timei ≤ 109
  • ui != vi

Visualization

Tap to expand
Number of Ways to Arrive at Destination INPUT 0 1 2 3 t=1 t=3 t=2 t=1 n = 4 roads = [[0,1,1],[0,2,3], [1,3,2],[2,3,1]] Start: 0, End: 3 Find shortest path count ALGORITHM STEPS 1 Initialize dist[0]=0, ways[0]=1 2 Dijkstra's Algorithm Use min-heap priority queue 3 Update Distances If shorter: reset ways count 4 Count Equal Paths If equal dist: add ways Final State: Node: 0 1 2 3 dist: 0 1 3 3 ways: 1 1 1 1 Path: 0 --> 1 --> 3 (time=3) FINAL RESULT 0 1 2 3 Output: 1 Only 1 shortest path exists with time = 3 [OK] Verified Key Insight: Dijkstra's algorithm finds shortest distances. To count paths, maintain a ways[] array: - If new shorter path found: ways[v] = ways[u] (reset count) - If equal distance path found: ways[v] += ways[u] (accumulate count). Return ways[n-1] mod 10^9+7 TutorialsPoint - Number of Ways to Arrive at Destination | Dijkstra with Path Counting
Asked in
Google 15 Facebook 12 Amazon 8
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen