Eadth First Search Algorithm
Eadth First Search Algorithm
PROBLEM DESCRIPTION: A standard BFS implementation puts each vertex of the graph into one
of two categories: Visited and Not Visited.The purpose of the
algorithm is to mark each vertex as visited while avoiding cycles.
ALGORITHM:
1. Define a sample graph as a dictionary, where keys are vertices, and values are lists of
adjacent vertices.
2. Call the bfs function with the graph and starting vertex (0).
3. Define two containers:
visited: A set to keep track of visited vertices to avoid revisiting them.
queue: A deque (double-ended queue) to implement the BFS exploration.
4. Add the root vertex to both visited and queue.
5. Create a loop that continues as long as the queue is not empty
i. Dequeue a vertex from the front of the queue.
ii. Print the vertex to show the traversal order.
iii. Iterate through all neighbors of the dequeued vertex in the graph.
▪ If a neighbor is not yet in the visited set, Add the neighbor to both visited and queue.
PROGRAM:
import
collections #
BFS algorithm
while queue:
# Dequeue a vertex from queue
vertex = queue.popleft()
print(str(vertex) + " ", end="")
OUTPUT: