You are on page 1of 1

def ao_star_algorithm(node, adjacency_list, h, solution_path):

if node in solution_path:
return h(node), solution_path[node]

if is_goal_node(node) or is_leaf_node(node, adjacency_list):


solution_path[node] = (None, 0) # No children and no cost for goal/leaf node
return h(node), solution_path

# Initialize best cost as infinity and best child as None


best_cost = float('inf')
best_child = None

# Iterate over children of the current node


for children, cost in adjacency_list.get(node, []):
# Calculate the heuristic cost for the child
child_cost, _ = ao_star_algorithm(children, adjacency_list, h, solution_path)
total_cost = cost + child_cost

# Update the best cost and best child if the total cost is lower
if total_cost < best_cost:
best_cost = total_cost
best_child = children

# Update the solution path with the best child and its cost
solution_path[node] = (best_child, best_cost)
return best_cost, solution_path

def is_goal_node(node):
# Define your goal check here
return node == 'Goal'

def is_leaf_node(node, adjacency_list):


# Check if the node is a leaf node (no children)
return len(adjacency_list.get(node, [])) == 0

# Example usage:
solution_path = {}
# Adjacency list of the graph
adjacency_list = {
'A': [('B', 1), ('C', 2)],
'B': [('D', 3), ('E', 4)],
'C': [('F', 5)],
'D': [('G', 6)],
'E': [('G', 4)],
'F': [('G', 3)],
'G': [] # Goal node has no children
}

# Heuristic values for each node


h_values = {
'A': 7,
'B': 6,
'C': 5,
'D': 4,
'E': 3,
'F': 2,
'G': 0 # Heuristic value for the goal node is always 0
}

total_cost, solution = ao_star_algorithm('A', adjacency_list, lambda n: h_values[n], solution_path)


print('Total cost:', total_cost)
print('Solution path:', solution)

You might also like