0% found this document useful (0 votes)
20 views3 pages

Ai Lab Program 2

The document describes the implementation of the A* Search algorithm, detailing the graph structure and heuristic values for nodes. It includes Python code that defines the graph, calculates the path from the start node 'A' to the goal node 'G', and outputs the path along with the costs. The algorithm uses a priority queue to explore the most promising paths based on actual and heuristic costs.

Uploaded by

Nidhi Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views3 pages

Ai Lab Program 2

The document describes the implementation of the A* Search algorithm, detailing the graph structure and heuristic values for nodes. It includes Python code that defines the graph, calculates the path from the start node 'A' to the goal node 'G', and outputs the path along with the costs. The algorithm uses a priority queue to explore the most promising paths based on actual and heuristic costs.

Uploaded by

Nidhi Rao
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 3

3 Implement A* Search algorithm

Node g(n) = Actual Cost from A Path from A

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

Node Heuristic (h) to Goal G

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)

for neighbor, cost in graph[current]:


new_g = g_score[current] + cost

if new_g < g_score[neighbor]:


came_from[neighbor] = current
g_score[neighbor] = new_g
f_score = new_g + heuristic[neighbor]
heapq.heappush(open_list, (f_score, neighbor))

return None, g_score

# Define the graph


graph = {
'A': [('B', 1), ('C', 3)],
'B': [('D', 3), ('E', 1)],
'C': [('F', 4)],
'D': [],
'E': [],
'F': [('G', 2)],
'G': []
}

# Heuristic values h(n)


heuristic = {
'A': 7,
'B': 6,
'C': 4,
'D': 6,
'E': 2,
'F': 2,
'G': 0
}
# Run A* Search
path, g_score = a_star_graph(graph, heuristic, 'A', 'G')

# Output
if path:
print(" Path found:", path)
else:
print(" No path found.")

# Show g(n) and h(n)


print("\n Node Costs:")
for node in graph:
g = g_score[node] if g_score[node] != float('inf') else "_"
h = heuristic[node]
print(f"Node {node}: g(n) = {g}, h(n) = {h}")

You might also like