BFS algorithm.docx
BFS algorithm.docx
Aim:
To implement the Breadth-First Search (BFS) algorithm in Python for traversing a graph
and finding a specific goal node
Algorithm:
● Create an empty queue (using deque) and add the starting node to it.
● Create an empty set visited to keep track of visited nodes.
Enqueue Neighbors:
● If the queue becomes empty and the goal is not found, return a failure message.
Program:
from collections import deque
while queue:
# Dequeue a node from the queue
current_node = queue.popleft()
print(f"Visiting: {current_node}")
# Run BFS
start_node = 'A'
goal_node = 'J'
result = bfs(graph, start_node, goal_node)
print(result)
Output:
Result: