OneCompiler

mgw BFS

128
def best_first_search(graph, current, goal):
    if current == goal:
        return [current]
    neighbors = sorted(graph[current], key=sort_by_weight)
    for neighbor, _ in neighbors:
        path = best_first_search(graph, neighbor, goal)
        if path is not None:
            return [current] + path
    return None

def sort_by_weight(node):
    return node[1]

graph = {
    'A': [('B', 5), ('C', 2)],
    'B': [('D', 1), ('E', 6)],
    'C': [('F', 3)],
    'D': [],
    'E': [('F', 4)],
    'F': []
}
start_node = 'A'
goal_node = 'F'

path = best_first_search(graph, start_node, goal_node)
if path:
    print("Best path:", path)
else:
    print("Path not found.")