0% found this document useful (0 votes)
5 views

AI4 my

The document outlines an experiment on implementing the A* search algorithm, detailing the setup of graphs, heuristics, and the algorithm's functionality to find the shortest path. It includes code for the algorithm, graph visualization using networkx, and a step-by-step display of the search process. The learning outcomes highlight the understanding of pathfinding, graph representation, and visualization techniques.

Uploaded by

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

AI4 my

The document outlines an experiment on implementing the A* search algorithm, detailing the setup of graphs, heuristics, and the algorithm's functionality to find the shortest path. It includes code for the algorithm, graph visualization using networkx, and a step-by-step display of the search process. The learning outcomes highlight the understanding of pathfinding, graph representation, and visualization techniques.

Uploaded by

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

ARITIFICIAL INTELLIGENCE LAB

Student Name: Rohit Choudhary UID:24MCI10212


Semester:2nd Section/Group:24MAM-1B
Subject Code:24CAP-674 Date:27/02/2025

EXPERIMENT NO - 4
Implement A* Search Algorithm

1. Aim/Task to be done:

1. Graph & Heuristic Setup – Nodes, edges, and estimated distances are defined.
2. A Algorithm* – Finds the shortest path using cost and heuristic values.
3. Path Search – Explores nodes, tracking the best route to the goal.
4. Visualization – Uses networkx to draw the graph and highlight paths.
5. Step-by-Step Display – Shows search progress with each iteration.

2. Code/Implementation:-

import heapq
import networkx as nx
import matplotlib.pyplot as plt

# Define the graph


graph = {
"A": {"B": 4, "C": 3},
"B": {"D": 2, "E": 5},
"C": {"F": 2, "G": 6},
"D": {"H": 3, "I": 4},
"E": {"I": 2},
"F": {"J": 3, "K": 1},
"G": {"K": 2},
"H": {"L": 4, "N": 2},
"I": {"M": 1},
"J": {"N": 3},
"K": {"O": 2},
"N": {"O": 4},
}

# Heuristic function (estimated


distance to goal 'O')
heuristic = {
"A": 10, "B": 8, "C": 7, "D": 6, "E": 6,
"F": 5, "G": 4, "H": 4, "I": 3, "J": 4,
"K": 2, "L": 3, "M": 2, "N": 2, "O": 0
}

# A* Search Algorithm
def a_star(graph, start, goal,
heuristic):
open_list = []
heapq.heappush(open_list, (0 +
heuristic[start], 0, start, [])) # (f,
g, node, path)
visited = set()
search_steps = [] # Store steps for
visualization

while open_list:
f, g, current, path =
heapq.heappop(open_list)
if current in visited:
continue

path = path + [current]

search_steps.append(path.copy(
)) # Store steps

if current == goal:
return path, g, search_steps #
Return shortest path and cost

visited.add(current)
for neighbor, cost in
graph.get(current, {}).items():
if neighbor not in visited:
g_new = g + cost
f_new = g_new +
heuristic[neighbor]
heapq.heappush(open_list,
(f_new, g_new, neighbor, path))

return None, float('inf'),


search_steps # No path found

# Run A* Algorithm
shortest_path, cost, search_steps =
a_star(graph, "A", "O", heuristic)

# Graph Visualization
G = nx.Graph()
for node in graph:
for neighbor, cost in
graph[node].items():
G.add_edge(node, neighbor,
weight=cost)

# Generate positions for nodes


pos = nx.spring_layout(G, seed=42)

# Display each step as a static image


for i, step in
enumerate(search_steps):
plt.figure(figsize=(8, 6))
plt.title(f"A* Step {i+1}: {' -
'.join(step)}")

# Draw entire graph


nx.draw(G, pos, with_labels=True,
node_color="lightgray",
edge_color="gray",
node_size=700, font_size=10)

# Highlight visited nodes in red


nx.draw_networkx_nodes(G, pos,
nodelist=step,
node_color="red",
node_size=700)

# Highlight path edges in green


path_edges = [(step[j], step[j+1])
for j in range(len(step)-1)]
nx.draw_networkx_edges(G, pos,
edgelist=path_edges,
edge_color="green", width=3)

plt.show()
3. Output:
4. Code/Implementation:-

import heapq
import networkx as nx
import matplotlib.pyplot as plt

# Define the graph with all letters and weighted edges


letter_graph = {
"J": {"O": 2, "K": 3}, "O": {"Y": 2, "P": 4}, "Y": {"I": 3},
"I": {"T": 2, "E": 4}, "T": {"A": 1}, "A": {"Z": 5}, "K": {"L": 2},
"P": {"M": 3}, "E": {"N": 2}, "Z": {"X": 4}, "M": {"Q": 3}, "N": {"R": 2},
"Q": {"S": 3}, "R": {"U": 2}, "X": {"V": 4}, "S": {"C": 3}, "U": {"D": 2},
"C": {"B": 3}, "D": {"F": 2}, "B": {"G": 4}, "F": {"H": 2}, "G": {"W": 3},
"H": {"V": 3}, "W": {"X": 3}, "L": {"M": 2}
}

# Define heuristic values (assumed heuristic distances to the goal 'A')


heuristic = {ch: abs(ord(ch) - ord('A')) for ch in letter_graph.keys()}

# A* Search Algorithm
def a_star(graph, start, goal, heuristic):
open_list = []
heapq.heappush(open_list, (0 + heuristic[start], 0, start, [])) # (f, g, node, path)
visited = set()
search_steps = [] # Store steps for visualization

while open_list:
f, g, current, path = heapq.heappop(open_list)
if current in visited:
continue

path = path + [current]


search_steps.append(path.copy()) # Store steps

if path == list("JOYITA"): # Stop once we find JOYITA


return path, g, search_steps # Return shortest path and cost

visited.add(current)
for neighbor, cost in graph.get(current, {}).items():
if neighbor not in visited:
g_new = g + cost
f_new = g_new + heuristic[neighbor]
heapq.heappush(open_list, (f_new, g_new, neighbor, path))

return None, float('inf'), search_steps # No path found

# Run A* Algorithm
shortest_path, cost, search_steps = a_star(letter_graph, "J", "A", heuristic)

# Graph Visualization
G = nx.Graph()
for node in letter_graph:
for neighbor, cost in letter_graph[node].items():
G.add_edge(node, neighbor, weight=cost)

# Generate positions for nodes


pos = nx.spring_layout(G, seed=42)

# Display each step as a static image


for i, step in enumerate(search_steps):
plt.figure(figsize=(8, 6))
plt.title(f"A* Step {i+1}: {' - '.join(step)}")

# Draw entire graph


nx.draw(G, pos, with_labels=True, node_color="lightgray", edge_color="gray",
node_size=700, font_size=10)

# Highlight visited nodes in red


nx.draw_networkx_nodes(G, pos, nodelist=step, node_color="red", node_size=700)

# Highlight path edges in green


path_edges = [(step[j], step[j+1]) for j in range(len(step)-1)]
nx.draw_networkx_edges(G, pos, edgelist=path_edges, edge_color="green",
width=3)

plt.show()

5. Output:-
6. Learning outcomes (What I have learned):

1. Learned A* finds the shortest path using cost (g) and heuristic (h).
2. Understood to represent graphs using dictionaries in Python.
3. Learned heuristics help guide the search efficiently.
4. Used heapq to implement the open list for optimal path selection.
5. Gained experience in using networkx and matplotlib to visualize search steps.

You might also like