Untitled

 avatar
unknown
plain_text
a year ago
945 B
1
Indexable
from queue import PriorityQueue

def best_first_search(graph, start, goal):
    visited = set()
    priority_queue = PriorityQueue()
    priority_queue.put((0, start))

    while not priority_queue.empty():
        cost, current_node = priority_queue.get()

        if current_node in visited:
            continue

        print("Visiting:", current_node)
        visited.add(current_node)

        if current_node == goal:
            print("Goal reached!")
            break

        for neighbor, neighbor_cost in graph[current_node]:
            if neighbor not in visited:
                priority_queue.put((neighbor_cost, neighbor))

# Example graph represented as an adjacency list
graph = {
    'A': [('B', 3), ('C', 6)],
    'B': [('A', 3), ('D', 2)],
    'C': [('A', 6), ('D', 1)],
    'D': [('B', 2), ('C', 1)]
}

start_node = 'A'
goal_node = 'D'

best_first_search(graph, start_node, goal_node)
Leave a Comment