Number of Ways to Arrive at Destination
LeetCode 1976 · ಮಧ್ಯಮ · ಪರಿಹಾರ, intuition ಮತ್ತು ಹಂತ ಹಂತದ ವಾಕ್ಥ್ರೂ
Dijkstra + ways: faster ⇒ copy ways, equal ⇒ add ways (mod 1e9+7).
ನಾನು Number of Ways to Arrive at Destination (LeetCode 1976) ಅನ್ನು ಹೀಗೆ ಪರಿಹರಿಸಿದೆ — Shortest Path / Dijkstra ಪ್ಯಾಟರ್ನ್ನ ಒಂದು ಮಧ್ಯಮ ಪ್ರಾಬ್ಲಮ್. ಕೆಳಗೆ: intuition, ಹಂತ ಹಂತದ approach, ನನ್ನ accepted Python ಕೋಡ್, animated test cases ಮತ್ತು line-by-line debugger.
ಕೆಳಗಿನ ವಿವರಣೆ ಇಂಗ್ಲಿಷ್ನಲ್ಲಿದೆ.
Intuition
Run Dijkstra from 0, but alongside each node's shortest time also keep how many shortest routes reach it. A strictly faster route replaces the count; an equally fast route adds its count.
Approach
- 1
Undirected adjacency list.
- 2
dist[0] = 0, ways[0] = 1, heap = [(0, 0)].
- 3
For each popped node and neighbour: a shorter time overwrites dist and ways and pushes the neighbour.
- 4
An equal time adds ways[node] to ways[neighbour].
- 5
Return ways[n-1].
ನಾನು ಹೇಗೆ ಪರಿಹರಿಸಿದೆ
Dijkstra with path countsPythonO(E log V) time
class Solution:
def countPaths(self, n: int, roads: List[List[int]]) -> int:
#dijsktra's
MOD = 1_000_000_007
dist = [float("inf")]*n
ways = [0]*n
min_heap = [(0,0)]
dist[0]=0
ways[0]=1
adj = defaultdict(list)
for u,v,w in roads:
adj[u].append((v,w))
adj[v].append((u,w))
while min_heap:
time,node = heapq.heappop(min_heap)
for adj_node,extra_time in adj[node]:
if time+extra_time<dist[adj_node]:
dist[adj_node]=time+extra_time
ways[adj_node]=ways[node]
heapq.heappush(min_heap,(time+extra_time,adj_node))
elif dist[adj_node]==time+extra_time:
ways[adj_node]=(ways[adj_node]+ways[node])%MOD
return ways[n-1]
Number of Ways to Arrive at Destination — ಪದೇ ಪದೇ ಕೇಳುವ ಪ್ರಶ್ನೆಗಳು
Number of Ways to Arrive at Destination ಹಿಂದಿನ intuition ಏನು?
Run Dijkstra from 0, but alongside each node's shortest time also keep how many shortest routes reach it. A strictly faster route replaces the count; an equally fast route adds its count.
Number of Ways to Arrive at Destination (LeetCode 1976) ಅನ್ನು ಹೇಗೆ ಪರಿಹರಿಸುವುದು?
1. Undirected adjacency list. 2. dist[0] = 0, ways[0] = 1, heap = [(0, 0)]. 3. For each popped node and neighbour: a shorter time overwrites dist and ways and pushes the neighbour. 4. An equal time adds ways[node] to ways[neighbour]. 5. Return ways[n-1].
Number of Ways to Arrive at Destination ನ time ಮತ್ತು space complexity ಎಷ್ಟು?
Time: O(E log V). Space: O(V + E). (Accepted approach: Dijkstra with path counts.)
Number of Ways to Arrive at Destination ನಲ್ಲಿ ಸಾಮಾನ್ಯ ತಪ್ಪುಗಳು ಯಾವುವು?
Take the modulo when adding counts. Stale heap entries can be skipped when time > dist[node] (an optional speed-up).