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

from heapq import heappop, heappush

def aStarAlgo(start, goal):


open_set = [(0, start)]
g = {start: 0}
parent = {start: None}

while open_set:
_, current = heappop(open_set)

if current == goal:
path = []
while current:
path.append(current)
current = parent[current]
path.reverse()
return path

for neighbor, cost in Graph_nodes.get(current, []):


new_cost = g[current] + cost
if neighbor not in g or new_cost < g[neighbor]:
g[neighbor] = new_cost
priority = new_cost + heuristic(neighbor)
heappush(open_set, (priority, neighbor))
parent[neighbor] = current

return None

def heuristic(n):
H_dist = {'A': 10, 'B': 8, 'C': 5, 'D': 7, 'E': 3, 'F': 6, 'G': 5, 'H': 3, 'I':
1, 'J': 0}
return H_dist.get(n, float('inf'))

Graph_nodes = {
'A': [('B', 6), ('F', 3)],
'B': [('C', 3), ('D', 2)],
'C': [('D', 1), ('E', 5)],
'D': [('C', 1), ('E', 8)],
'E': [('I', 5), ('J', 5)],
'F': [('G', 1), ('H', 7)],
'G': [('I', 3)],
'H': [('I', 2)],
'I': [('E', 5), ('J', 3)],
}
print(aStarAlgo('A', 'J'))

OUTPUT:

['A', 'F', 'G', 'I', 'J']

You might also like