Advertisement
jabela

Dijkstra and A star compared

Dec 24th, 2023 (edited)
592
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.26 KB | None | 0 0
  1. import heapq
  2.  
  3. def reconstruct_path(came_from, current):
  4.     """Reconstruct the path from start to current node."""
  5.     path = []
  6.     while current in came_from:
  7.         path.append(current)
  8.         current = came_from[current]
  9.     return path[::-1]
  10.  
  11. def dijkstra(grid, start, end):
  12.     """Dijkstra's algorithm to find the shortest path in a grid."""
  13.     rows, cols = len(grid), len(grid[0])
  14.     visited = set()
  15.     came_from = {}
  16.     queue = [(0, start)]
  17.     explored_nodes = []
  18.  
  19.     while queue:
  20.         current_dist, current = heapq.heappop(queue)
  21.         if current in visited:
  22.             continue
  23.         visited.add(current)
  24.         came_from[current] = None if current == start else prev
  25.         explored_nodes.append(current)
  26.  
  27.         if current == end:
  28.             return current_dist, reconstruct_path(came_from, current), explored_nodes
  29.  
  30.         for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
  31.             x, y = current[0] + dx, current[1] + dy
  32.             prev = current
  33.             if 0 <= x < rows and 0 <= y < cols and grid[x][y] == 0 and (x, y) not in visited:
  34.                 heapq.heappush(queue, (current_dist + 1, (x, y)))
  35.  
  36.     return -1, [], explored_nodes
  37.  
  38. def manhattan_distance(start, end):
  39.     """Calculate the Manhattan distance between two points."""
  40.     return abs(start[0] - end[0]) + abs(start[1] - end[1])
  41.  
  42. def a_star(grid, start, end):
  43.     """A* algorithm to find the shortest path in a grid."""
  44.     rows, cols = len(grid), len(grid[0])
  45.     visited = set()
  46.     came_from = {}
  47.     queue = [(manhattan_distance(start, end), 0, start)]
  48.     explored_nodes = []
  49.  
  50.     while queue:
  51.         total_cost, current_dist, current = heapq.heappop(queue)
  52.         if current in visited:
  53.             continue
  54.         visited.add(current)
  55.         came_from[current] = None if current == start else prev
  56.         explored_nodes.append(current)
  57.  
  58.         if current == end:
  59.             return current_dist, reconstruct_path(came_from, current), explored_nodes
  60.  
  61.         for dx, dy in [(-1, 0), (1, 0), (0, -1), (0, 1)]:
  62.             x, y = current[0] + dx, current[1] + dy
  63.             prev = current
  64.             if 0 <= x < rows and 0 <= y < cols and grid[x][y] == 0 and (x, y) not in visited:
  65.                 heapq.heappush(queue, (current_dist + 1 + manhattan_distance((x, y), end), current_dist + 1, (x, y)))
  66.  
  67.     return -1, [], explored_nodes
  68.  
  69. # Example grid and start/end points
  70. grid = [
  71.     [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
  72.     [0, 1, 1, 1, 1, 0, 1, 1, 1, 0],
  73.     [0, 1, 0, 0, 0, 0, 1, 0, 0, 0],
  74.     [0, 1, 0, 1, 1, 1, 1, 0, 1, 0],
  75.     [0, 0, 0, 0, 0, 0, 0, 0, 1, 0],
  76.     [0, 1, 1, 1, 1, 1, 1, 0, 1, 0],
  77.     [0, 1, 0, 0, 0, 0, 0, 0, 1, 0],
  78.     [0, 1, 0, 1, 1, 1, 1, 0, 1, 0],
  79.     [0, 1, 0, 1, 0, 0, 0, 0, 1, 0],
  80.     [0, 0, 0, 0, 0, 1, 1, 1, 1, 0]
  81. ]
  82. start = (0, 0)
  83. end = (9, 9)
  84.  
  85. # Run both algorithms
  86. dijkstra_result, dijkstra_path, dijkstra_explored = dijkstra(grid, start, end)
  87. a_star_result, a_star_path, a_star_explored = a_star(grid, start, end)
  88.  
  89. print(f"Dijkstra: Path length = {dijkstra_result}")
  90. print(f"A*      : Path length = {a_star_result}")
  91.  
  92. print(f"Dijkstra: Nodes explored = {len(dijkstra_explored)} Explored: {dijkstra_explored}")
  93. print(f"A*      : Nodes explored = {len(a_star_explored)} Explored: {a_star_explored} ")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement