Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

class Node:

def __init__(self, state, g=0, h=0):


self.state = state
self.g = g
self.h = h
self.f = g + h

def expand(node):
return [Node("B"), Node("C"), Node("D")]

def cost(node1, node2):


return 1

def heuristic(state):
return 1

def ao_star(start, goal, heuristic):


open_set = {start}
closed_set = set()
while open_set:
current = min(open_set, key=lambda node: node.f)
if current.state == goal.state:
return current
open_set.remove(current)
closed_set.add(current)
for neighbor in expand(current):
if neighbor in closed_set:
continue
if neighbor not in open_set or neighbor.g > current.g + cost(current,
neighbor):
neighbor.g = current.g + cost(current, neighbor)
neighbor.h = heuristic(neighbor.state)
neighbor.f = neighbor.g + neighbor.h
open_set.add(neighbor)
return None

initial_state = Node("A")
goal_state = Node("D")

result = ao_star(initial_state, goal_state, heuristic)

if result:
print("Goal reached!")
print("Final state:", result.state)
print("Total cost:", result.f)
else:
print("Goal not found.")

OUTPUT:

Goal reached!
Final state: D
Total cost: 2

You might also like