fork download
  1. from queue import PriorityQueue
  2.  
  3. # Define the graph
  4. graph = {
  5. 'A': {'D': 3, 'B': 5, 'C': 8},
  6. 'D': {'F': 7},
  7. 'B': {'E': 2},
  8. 'C': {'F': 3, 'E': 3},
  9. 'F': {'G': 1},
  10. 'E': {'H': 1},
  11. 'H': {'G': 2}
  12. }
  13.  
  14. # Define heuristic values
  15. heuristic = {
  16. 'A': 40,
  17. 'D': 35,
  18. 'B': 32,
  19. 'C': 25,
  20. 'E': 19,
  21. 'F': 17,
  22. 'H': 10,
  23. 'G': 0 # Goal
  24. }
  25.  
  26. def a_star_algorithm(start, goal):
  27. # Priority queue to store nodes along with their cost
  28. open_set = PriorityQueue()
  29. open_set.put((0, start)) # (total_cost, node)
  30.  
  31. # Dictionary to store the cost of reaching each node
  32. g_costs = {start: 0}
  33.  
  34. # Dictionary to reconstruct the path
  35. came_from = {}
  36.  
  37. while not open_set.empty():
  38. _, current = open_set.get()
  39.  
  40. if current == goal:
  41. path = []
  42. while current in came_from:
  43. path.append(current)
  44. current = came_from[current]
  45. path.append(start)
  46. path.reverse()
  47. return path, g_costs[goal]
  48.  
  49. for neighbor, weight in graph.get(current, {}).items():
  50. tentative_g_cost = g_costs[current] + weight
  51. if neighbor not in g_costs or tentative_g_cost < g_costs[neighbor]:
  52. g_costs[neighbor] = tentative_g_cost
  53. f_cost = tentative_g_cost + heuristic[neighbor]
  54. open_set.put((f_cost, neighbor))
  55. came_from[neighbor] = current
  56.  
  57. return None, float('inf') # If no path is found
  58.  
  59. # Run the A* algorithm
  60. start_node = 'A'
  61. goal_node = 'G'
  62. path, cost = a_star_algorithm(start_node, goal_node)
  63.  
  64. print("Path:", path)
  65. print("Cost:", cost)
Success #stdin #stdout 0.09s 14176KB
stdin
Standard input is empty
stdout
Path: ['A', 'C', 'F', 'G']
Cost: 12