#1976

Number of Ways to Arrive at Destination

Medium
Dynamic ProgrammingGraph TheoryTopological SortShortest PathGraph TraversalDijkstra's AlgorithmDynamic Programming
LeetCode ↗

Approaches

Brute ForceOptimal
Complexity Comparison
Brute ForceOptimal Solution
Time
O(n²)
O(n log n)
Space
O(1)
O(n)
💡

Intuition

Time O(n log n)Space O(n)

The optimal approach uses Dijkstra's algorithm to find the shortest path from intersection 0 to all other intersections. Then, we can use dynamic programming to count the number of ways to reach the destination using only the edges that contribute to the shortest path.

⚙️

Algorithm

3 steps
  1. 1Step 1: Use Dijkstra's algorithm to find the shortest time from intersection 0 to all intersections.
  2. 2Step 2: Create a DP array where dp[i] represents the number of ways to reach intersection i in the shortest time.
  3. 3Step 3: Traverse the graph again, and for each edge that contributes to the shortest path, update the DP array accordingly.
solution.py32 lines
1# Full working Python code
2import heapq
3from collections import defaultdict
4
5def countPaths(n, roads):
6    graph = defaultdict(list)
7    for u, v, time in roads:
8        graph[u].append((v, time))
9        graph[v].append((u, time))
10
11    # Step 1: Dijkstra's algorithm
12    dist = [float('inf')] * n
13    dist[0] = 0
14    pq = [(0, 0)]  # (time, node)
15    while pq:
16        time, node = heapq.heappop(pq)
17        for neighbor, travel_time in graph[node]:
18            if time + travel_time < dist[neighbor]:
19                dist[neighbor] = time + travel_time
20                heapq.heappush(pq, (dist[neighbor], neighbor))
21
22    # Step 2: DP array
23    dp = [0] * n
24    dp[0] = 1
25
26    # Step 3: Count paths
27    for node in range(n):
28        for neighbor, travel_time in graph[node]:
29            if dist[node] + travel_time == dist[neighbor]:
30                dp[neighbor] = (dp[neighbor] + dp[node]) % (10**9 + 7)
31
32    return dp[n - 1]

Complexity note: The time complexity is O(n log n) due to Dijkstra's algorithm, which uses a priority queue to efficiently find the shortest paths. The space complexity is O(n) for storing the graph and the DP array.

  • 1Using Dijkstra's algorithm helps efficiently find the shortest paths in a weighted graph.
  • 2Dynamic programming allows us to count the number of ways to reach the destination using only valid edges.

Solutions and explanations are original Tejav content. Problem titles © LeetCode — use the LeetCode button above for the full problem statement.