oneby7

Advanced Graphs Weighted shortest paths

480. Number of Ways to Arrive at Destination

Medium

A city has n intersections, numbered from 0 to n - 1, joined by two-way roads. Each roads[i] = [u, v, t] means a road joins intersections u and v, and driving along it takes t minutes in either direction.

You start at intersection 0 and want to reach intersection n - 1 as quickly as possible. Return the number of different routes that take the least possible time. The number can be huge, so return it modulo 109 + 7. If no route leads to intersection n - 1, return 0.

A route is a sequence of roads, each one starting where the last one ended. Two routes are different if they pass through a different sequence of intersections.

Example 1

23435217012345

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

Output: 3

Explanation: The least time is 8 minutes, and three routes take it: 0 → 1 → 3 → 5, 0 → 2 → 3 → 5 and 0 → 1 → 4 → 5. The road from 2 straight to 5 gives a route of 10 minutes, which is slower.

Example 2

448012

Input: n = 3, roads = [[1, 0, 4], [2, 1, 4], [0, 2, 8]]

Output: 2

Explanation: The road straight from 0 to 2 takes 8 minutes, and so does 0 → 1 → 2. That route drives both of its roads from their second intersection to their first, which is allowed.

Example 3

10⁹1601234

Input: n = 5 roads = [[0, 1, 1000000000], [1, 2, 1], [3, 4, 6]]

Output: 0

Explanation: No road leaves the group of intersections 0, 1 and 2, so intersection 4 cannot be reached.

Check your understanding

Work out the answer for this input before you write any code.

n = 5 roads = [[0, 1, 1], [1, 4, 4], [0, 2, 2], [2, 4, 3], [0, 3, 3], [3, 4, 3], [0, 4, 7]]

Constraints

  • 1 ≤ n ≤ 105
  • 0 ≤ roads.length ≤ 105
  • roads[i] = [u, v, t], with 0 ≤ u, v ≤ n - 1, u ≠ v and 1 ≤ t ≤ 109
  • At most one road joins any two intersections.

Clarifying questions

What you would ask an interviewer before writing any code.

Hints

Interview follow-ups

Runs in your browser
Code
Runs in your browser for now · some things may not work as expectedLn 1, Col 1

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.