Taking on a new challenge: solving GeeksforGeeks POTD daily and sharing my solutions! π»π₯
The goal: sharpen problem-solving skills, level up coding, and learn something new every day. Follow my journey! π
100DaysOfCode #CodingChallenge #ProblemSolving #GeeksforGeeks #DeveloperJourney
Problem:
https://www.geeksforgeeks.org/problems/number-of-ways-to-arrive-at-destination/1
Number of Ways to Arrive at Destination
Difficulty: Medium Accuracy: 61.13%
You are given an undirected weighted graph with V vertices numbered from 0 to V-1 and E edges, represented as a 2D array edges[][], where edges[i] = [ui, vi, timei] means that there is an undirected edge between nodes ui and vi that takes timei minutes to reach.
Your task is to return in how many ways you can travel from node 0 to node V - 1 in the shortest amount of time.
Examples:
Input: V = 4, edges[][] = [[0, 1, 2], [1, 2, 3], [0, 3, 5], [1, 3, 3], [2, 3, 4]]

Output: 2
Explanation: The shortest path from 0 to 3 is 5.
Two ways to reach 3 in 5 minutes are:
0 -> 3
0 -> 1 -> 3
Input: V = 6, edges[][] = [[0, 2, 3], [0, 4, 2], [0, 5, 7], [2, 3, 1], [2, 5, 5], [5, 3, 3], [5, 1, 4], [1, 4, 1], [4, 5, 5]]

Output: 4
Explanation: The shortest path from 0 to 5 is 7.
Four ways to reach 5 in 7 minutes are:
0 -> 5
0 -> 4 -> 5
0 -> 4 -> 1 -> 5
0 -> 2 -> 3 -> 5
Constraints:
1 β€ V β€ 200
V - 1 β€ edges.size() β€ V * (V - 1) / 2
0 β€ ui, vi β€ V - 1
1 β€ timei β€ 105
ui != vi
Solution:
class Solution:
def countPaths(self, V, edges):
g = [[] for _ in range(V)]
for u, v, w in edges:
g[u].append((v, w))
g[v].append((u, w))
import heapq
dist = [10**18] * V
ways = [0] * V
dist[0] = 0
ways[0] = 1
pq = [(0, 0)]
mod = 10**9+7
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in g[u]:
nd = d + w
if nd < dist[v]:
dist[v] = nd
ways[v] = ways[u]
heapq.heappush(pq, (nd, v))
elif nd == dist[v]:
ways[v] = (ways[v] + ways[u]) % mod
return ways[V-1] % mod
Top comments (0)