Darveivoldavara

dijkstra

Nov 17th, 2023 (edited)
826
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.86 KB | None | 0 0
  1. from heapq import heappush, heappop
  2.  
  3. def dijkstra(graph, start):
  4.     n = len(graph)
  5.     distance = [float('inf')] * n
  6.     distance[start] = 0
  7.     queue = [(0, start)]
  8.     visited = [False] * n
  9.     path = [-1] * n
  10.     end = 0
  11.  
  12.     while queue:
  13.         dist, current = heappop(queue)
  14.  
  15.         if visited[current]:
  16.             continue
  17.         visited[current] = True
  18.  
  19.         if current == end:
  20.             break
  21.  
  22.         for neighbor, weight in graph[current]:
  23.             if dist + weight < distance[neighbor]:
  24.                 path[neighbor] = current
  25.                 distance[neighbor] = dist + weight
  26.                 heappush(queue, (distance[neighbor], neighbor))
  27.  
  28.     final_path = []
  29.     current = end
  30.     while current != -1:
  31.         final_path.append(current + 1)
  32.         current = path[current]
  33.     return distance[end], final_path[::-1]
Advertisement
Add Comment
Please, Sign In to add comment