nathanwailes

Dijkstra's algorithm

Apr 14th, 2024 (edited)
897
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.05 KB | None | 0 0
  1. """ Dijkstra's Algorithm finds the shortest path between a given node (which is called the "source node") and all other nodes in a graph.
  2.  
  3. A* algorithm is just like Dijkstra's algorithm, and the only difference is that A* tries to look for a better path by using a heuristic function, which gives priority to nodes that are supposed to be better than others while Dijkstra's just explore all possible ways.
  4.  
  5. Mnemonic summary: Dijkstra is a BFS with three changes:
  6. - edges are 2-tuples
  7.   - The edge entries in the graph are 2-tuples rather than just vertex values or Node objects. Each edge entry has a second 'distance/weight' integer value.
  8. - a heap is used
  9.   - A heap is used rather than a deque. The heap value is a 2-tuple with the distance first, then the vertex
  10. - another dict tracks shortest distance to each vertex
  11. """
  12. import heapq
  13.  
  14. def dijkstra(graph, start):
  15.     total_distance_to = {vertex: float('infinity') for vertex in graph}
  16.     total_distance_to[start] = 0
  17.    
  18.     hp = [(0, start)]  # (distance, vertex)  # Heap to hold vertices to be processed
  19.     while hp:
  20.         current_vertex_distance, current_vertex = heapq.heappop(hp)  # Get vertex with smallest distance
  21.         if current_vertex_distance > total_distance_to[current_vertex]:  # Only process a vertex once
  22.             continue
  23.  
  24.         # Most of the logic is in the neighbor-handling block
  25.         for neighbor, marginal_distance in graph[current_vertex]:  # If a shorter path is found
  26.             total_neighbor_distance = current_vertex_distance + marginal_distance
  27.             if total_neighbor_distance < total_distance_to[neighbor]:
  28.                 total_distance_to[neighbor] = total_neighbor_distance
  29.  
  30.                 # Any time we find a shorter distance to a vertex, we want to recalculate the distances to its neighbors.
  31.                 heapq.heappush(hp, (total_neighbor_distance, neighbor))
  32.     return total_distance_to
  33.  
  34. graph = {
  35.     'a': [('b', 1), ('c', 2)],
  36.     'b': [('d', 3), ('e', 4)],
  37.     'c': [],
  38.     'd': [],
  39.     'e': []
  40. }
  41. print(dijkstra(graph, 'a'))
Advertisement
Add Comment
Please, Sign In to add comment