AI4 my
AI4 my
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
# 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
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))
# 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)
plt.show()
3. Output:
4. Code/Implementation:-
import heapq
import networkx as nx
import matplotlib.pyplot as plt
# 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
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))
# 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)
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.