Skip to content

Instantly share code, notes, and snippets.

@Ifihan
Created March 23, 2025 22:16
Show Gist options
  • Save Ifihan/4b08bcf3a0e16024c71edd29badfab56 to your computer and use it in GitHub Desktop.
Save Ifihan/4b08bcf3a0e16024c71edd29badfab56 to your computer and use it in GitHub Desktop.
Number of Ways to Arrive at Destination

Question

Approach

To solve the problem, I used Dijkstra’s algorithm to find the shortest path from node 0 to node n - 1. While doing that, I kept track of the number of ways to reach each node using a ways array. I initialized the distance to node 0 as 0 and the number of ways to reach it as 1. As I traversed the graph using a min-heap, I updated the shortest distance to each node. If I found a shorter path, I reset the ways count; if I found an equally short path, I added to the existing count. Finally, I returned the number of ways to reach the destination node in the shortest time, modulo (10^9 + 7).

Implementation

class Solution:
    def countPaths(self, n: int, roads: List[List[int]]) -> int:
        MOD = 10**9 + 7
        graph = [[] for _ in range(n)]

        for u, v, time in roads:
            graph[u].append((v, time))
            graph[v].append((u, time))

        min_time = [float('inf')] * n
        ways = [0] * n
        min_time[0] = 0
        ways[0] = 1
        pq = [(0, 0)] 

        while pq:
            curr_time, node = heapq.heappop(pq)

            if curr_time > min_time[node]:
                continue

            for nei, t in graph[node]:
                new_time = curr_time + t

                if new_time < min_time[nei]:
                    min_time[nei] = new_time
                    ways[nei] = ways[node]
                    heapq.heappush(pq, (new_time, nei))
                elif new_time == min_time[nei]:
                    ways[nei] = (ways[nei] + ways[node]) % MOD

        return ways[n - 1]

Complexities

  • Time: O(n + e)
  • Space: O(n + e)
image
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment