Informed BFS
from queue import PriorityQueue
graph = {
'A': [('B', 3), ('C', 6), ('D', 5)],
'B': [('E', 9), ('F', 8)],
'C': [('G', 12), ('H', 14)],
'D': [('I', 7)],
'E': [('G', 10)],
'F': [],
'G': [],
'H': [],
'I': [('J', 1), ('K', 10), ('L', 2)],
'J': [],
'K': [],
'L': []
}
heuristic = {
'A': 10,
'B': 8,
'C': 8,
'D': 6,
'E': 5,
'F': 6,
'G': 0,
'H': 0,
'I': 4,
'J': 1,
'K': 10,
'L': 2
}
def best_first_search(graph, start, goal, heuristic):
visited = set()
pq = PriorityQueue()
pq.put((heuristic[start], start))
while not pq.empty():
_, current_node = pq.get()
if current_node == goal:
print("Goal reached:", current_node)
return
if current_node not in visited:
print("Visiting:", current_node)
visited.add(current_node)
neighbors = graph[current_node]
for neighbor, cost in neighbors:
if neighbor not in visited:
pq.put((heuristic[neighbor], neighbor))
print("Goal not reached")
start_node = 'A'
goal_node = 'G'
best_first_search(graph, start_node, goal_node, heuristic)
Comments
Post a Comment