22IZ014 HARSHAN R - Exercise 2 - A - and AO - Algorithm
22IZ014 HARSHAN R - Exercise 2 - A - and AO - Algorithm
AIM:
To implement A* and AO* algorithm.
A* Algorithm Code:
import heapq
visited = set()
while pq:
f, g, current, path = heapq.heappop(pq)
if current in visited:
continue
# Expand neighbors
for neighbor, cost in graph[current]:
if neighbor not in visited:
new_g = g + cost
new_f = new_g + heuristic[neighbor]
heapq.heappush(pq, (new_f, new_g, neighbor, path +
[neighbor]))
# Input reading
N = int(input())
E = int(input())
edges = [tuple(map(int, input().split())) for _ in range(E)]
H = int(input())
heuristics = [tuple(map(int, input().split())) for _ in range(H)]
start = int(input())
goal = int(input())
# Execute A* search
a_star_search(N, E, edges, H, heuristics, start, goal)
\
OUTPUT:
Sample Input Sample Output
5
6 Visiting: 1
Visiting: 3
Visiting: 5
121 Goal reached: 5
134 Path: [1, 3, 5]
242 Cost: 5
255
351
4535
17
26
32
41
50
8 Visiting: 1
10 Visiting: 2
121 Visiting: 3
134 Visiting: 4
245 Visiting: 6
342 Visiting: 8
356 Goal reached: 8
463 Path: [1, 2, 4, 6, 8]
478 Cost: 13
571
684
7828
1 10
28
37
45
56
63
72
80