Exercise 2
Exercise 2
graph = {
'A': [('B', 2), ('E', 3)],
'B': [('A',2), ('C',1)],
'C': [('B',1), ('G',9)],
'E': [('A',3), ('D',6)],
'D': [('E',6), ('G',1)],
'G': [('C',9), ('D',1)]
}
while open_list:
f, current_node, path, g = heapq.heappop(open_list)
if current_node == goal:
print(f"Path: {' -> '.join(path)} \nCost: {g}") return
closed_list.add(current_node)
for neighbor, cost in graph.get(current_node, []):
if neighbor not in closed_list:
new_g = g + cost
new_f = new_g + heuristic[neighbor]
heapq.heappush(open_list, (new_f, neighbor, path + [neighbor],
new_g))
start_node = 'A'
goal_node = 'G'
a_star_search(start_node, goal_node)
Output:
Conclusion:
A* is an efficient and optimal pathfinding algorithm that combines actual travel
costs and heuristic estimates. It guarantees the shortest path if the heuristic is
admissible and is widely used in AI and robotics for tasks like route planning.
Its performance improves with a better heuristic, balancing accuracy and
efficiency.
Thus, the implementation of A* Graph algorithm is successfully executed.