0% found this document useful (0 votes)
12 views3 pages

A Star Code

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

A Star Code

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

from queue import PriorityQueue

def a_star(graph, heuristics, start, goal):

# Priority queue to store (cost, current_node, path)

open_list = PriorityQueue()

open_list.put((0, start, [start]))

# Set to keep track of explored nodes

closed_list = set()

while not open_list.empty():

# Get the node with the lowest cost (f = g + h)

cost, current_node, path = open_list.get()

# If we reached the goal, return the path and cost

if current_node == goal:

return path, cost

closed_list.add(current_node)

# Explore neighbors

for neighbor, edge_cost in graph[current_node].items():

if neighbor not in closed_list:

# Calculate new cost

new_cost = cost + edge_cost + heuristics[neighbor] - heuristics[current_node]

new_path = path + [neighbor]

open_list.put((new_cost, neighbor, new_path))

# If the goal is not reachable, return None


return None, float('inf')

# Define the graph based on the provided image

graph = {

'A': {'B': 6, 'D': 3},

'B': {'A': 6, 'C': 3, 'D': 2},

'C': {'B': 3, 'E': 5, 'D': 1},

'D': {'A': 3, 'B': 2, 'C': 1, 'F': 6},

'E': {'C': 5, 'J': 5, 'G': 3},

'F': {'D': 6, 'G': 1, 'H': 7},

'G': {'F': 1, 'I': 3, 'E': 3},

'H': {'F': 7, 'I': 2},

'I': {'G': 3, 'H': 2, 'J': 3},

'J': {'I': 3, 'E': 5}

# Define the heuristics (h(n)) based on the image

heuristics = {

'A': 10,

'B': 8,

'C': 5,

'D': 7,

'E': 3,

'F': 6,

'G': 5,

'H': 3,

'I': 1,

'J': 0 # Goal node, heuristic is 0

}
# Define the start and goal nodes

start_node = 'A'

goal_node = 'J'

# Run the A* algorithm

path, cost = a_star(graph, heuristics, start_node, goal_node)

# Output the result

if path:

print(f"Path found: {' -> '.join(path)} with total cost: {cost}")

else:

print("No path found.")

You might also like