AlgoMaster Logo

Number of Ways to Arrive at Destination

Ashish

Ashish Pratap Singh

medium

Problem Description

Solve it on LeetCode

Approaches

1. Dijkstra's Algorithm with DFS

Intuition:

In this approach, we'll use the famous Dijkstra's Algorithm to find the shortest path from the source to the destination. After finding the shortest path, we can perform a DFS from the destination to the source to count all the possible paths matching this shortest path length. This approach is still efficient for the input size allowed by the problem constraints.

Algorithm:

  1. Utilize Dijkstra's Algorithm to ensure all minimum weights from the source to all other nodes.
  2. Once the shortest path weights are captured, use DFS from the destination to the source counting all possible paths that equal this shortest path weight.
  3. Ensure to mod the result by (10^9 + 7).

Code:

2. Dijkstra's Algorithm with Dynamic Programming

Intuition:

In this approach, instead of using DFS to count paths after Dijkstra's, we integrate the counting mechanism into Dijkstra’s Algorithm itself. This involves maintaining a separate array to count the number of ways to reach each node, updating it as we discover the shortest paths.

Algorithm:

  1. Use Dijkstra's Algorithm to compute both the shortest distances and count ways dynamically.
  2. Maintain an array to track the number of ways to reach a node when processing its neighbors in the priority queue.
  3. If a shorter path found to a node, update the path count to that node as that of the current node.
  4. If another equal shortest path found, add the current node's path count to that node's path count.

Code: