Skip to main content
LeetCode 1976, Medium. Topics: Dynamic Programming, Graph Theory, Topological Sort, Shortest Path, Dijkstra’s Algorithm. View on LeetCode. Generate this problem as a practice environment: tested reference solution, 17 parametrized pytest cases, and a playground notebook:

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] = [u<sub>i</sub>, v<sub>i</sub>, time<sub>i</sub>] means that there is a road between intersections u<sub>i</sub> and v<sub>i</sub> that takes time<sub>i</sub> 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 10<sup>9</sup> + 7.

Examples

Example 1

Constraints

  • 1 <= n <= 200
  • n - 1 <= roads.length <= n * (n - 1) / 2
  • roads[i].length == 3
  • 0 <= u<sub>i</sub>, v<sub>i</sub> <= n - 1
  • 1 <= time<sub>i</sub> <= 10<sup>9</sup>
  • u<sub>i</sub> != v<sub>i</sub>
  • There is at most one road connecting any two intersections.
  • You can reach any intersection from any other intersection.

Solution

Reference implementation from solution.py on GitHub, full suite in test_solution.py:

Complexity

Tags

NeetCode All.
Last modified on September 7, 2026