Best first search
import heapq
def best_first_search(graph, start, goal):
pq = [(0, start)] # Priority queue (cost, node)
visited = set() # Track visited nodes
while pq:
cost, node = heapq.heappop(pq)
if node in visited:
continue
visited.add(node)
if node == goal:
return f"Goal {goal} reached with cost {cost}"
for neighbor, weight in graph[node]:
if neighbor not in visited:
heapq.heappush(pq, (weight, neighbor))
return "Goal not reachable"
graph = {
'A': [('B', 1), ('C', 4)],
'B': [('D', 2), ('E', 5)],
'C': [('F', 1)],
'D': [], 'E': [], 'F': []
}
print(best_first_search(graph, 'A', 'F'))
BFS
Comments
Post a Comment