imashutosh51

Shortest distance from source node to all the nodes

Mar 22nd, 2026 (edited)
67
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.37 KB | None | 0 0
  1. """
  2. Problem:
  3. Find shortest distance from source to all nodes in a graph with non-negative weights.
  4.  
  5. ------------------------------------------------------------
  6.  
  7. Observation:
  8. If we already know the shortest distance to a node,
  9. we can try to improve distances of its neighbors.
  10.  
  11. Since weights are non-negative,
  12. the node with smallest distance is always correct.
  13.  
  14. ------------------------------------------------------------
  15.  
  16. Intuition:
  17. Always pick the closest node first and expand from it.
  18.  
  19. - Maintain dist[] → shortest distance
  20. - Use min-heap → to get closest node
  21. - Relax edges → update neighbor distance if better
  22.  
  23. If a node appears again in heap with worse distance,
  24. skip it (outdated path).
  25.  
  26. ------------------------------------------------------------
  27.  
  28. Code Intuition:
  29. - Initialize dist[src] = 0, rest = ∞
  30. - Push (0, src) into heap
  31. - While heap:
  32.    - pop smallest distance node
  33.    - skip if outdated
  34.    - relax all neighbors
  35.  
  36. ------------------------------------------------------------
  37.  
  38. Time Complexity:
  39. For each time, a verted a popped from the min heap so O(Vlog(V))
  40. for each time, an edge is pushed into the min heap so O(Elog(E))
  41. so total is sum of both ie. O(V+E(logV)) because E=V^2 when all nodes are connected to each other so Elog(E) becomes Elog(V^2) ie. 2Elog(V) ie. Elog(V) so Elog(V)+Vlog(V) equal (E+V)log(V)
  42. """
  43.  
  44. from collections import defaultdict
  45. from heapq import heappush,heappop
  46. import math
  47. class Solution:
  48.     # Returns shortest distances from src to all other vertices
  49.     def dijkstra(self, v, edges, src):
  50.         graph=defaultdict(list)
  51.         for a,b,c in edges:
  52.             graph[a].append((b,c))
  53.             graph[b].append((a,c))
  54.         # print(graph)
  55.         dist=[math.inf]*v
  56.         dist[src]=0
  57.         heap=[]
  58.         heappush(heap,(0,src))
  59.         while len(heap)>0:
  60.             cur_dis,node=heappop(heap)
  61.             if cur_dis>dist[node]: #this stops going back to the same node but the dist to go to the same node is less now.In djktra same node can come in the heap multiple times so the other route already distance less so no need to consider this route.
  62.                 continue
  63.             for neigh, w in graph[node]:
  64.                 if cur_dis+w< dist[neigh]:
  65.                     dist[neigh]=cur_dis+w
  66.                     heappush(heap,(cur_dis+w, neigh))
  67.         return dist
  68.            
  69.        
Advertisement
Add Comment
Please, Sign In to add comment