Ai Lab Program 2
Ai Lab Program 2
A 0 A
B 1 A→B
C 3 A→C
D 4 A→B→D
E 2 A→B→E
F 7 A→C→F
G 9 A→C→F→G
Heuristic Values
A 7 A
B 6 /\
B C
C 4
/\ \
D 6
D E F
E 2
/
F 2
G
G 0
import heapq
def a_star_graph(graph, heuristic, start, goal):
open_list = []
heapq.heappush(open_list, (0, start))
came_from = {}
g_score = {node: float('inf') for node in graph}
g_score[start] = 0
while open_list:
_, current = heapq.heappop(open_list)
if current == goal:
# Trace the path back
path = []
while current in came_from:
path.append(current)
current = came_from[current]
path.append(start)
return path[::-1], g_score # also return g(n)
# Output
if path:
print(" Path found:", path)
else:
print(" No path found.")