0% found this document useful (0 votes)
21 views

31 - Data Structure - Breadth First Traversal

Uploaded by

laraib
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views

31 - Data Structure - Breadth First Traversal

Uploaded by

laraib
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 4

Data Structure - Breadth First

Traversal

Bhabani Shankar Pradhan


Breadth First Search (BFS) algorithm traverses a graph in a breadthward
motion and uses a queue to remember to get the next vertex to start a search,
when a dead end occurs in any iteration.

As in the example given above, BFS algorithm traverses from A to B to E to F


first then to C and G lastly to D. It employs the following rules.

 Rule 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it.
Insert it in a queue.

 Rule 2 − If no adjacent vertex is found, remove the first vertex from the
queue.

 Rule 3 − Repeat Rule 1 and Rule 2 until the queue is empty.

Step Traversal Description


1 Initialize the queue.

We start from
2 visiting S (starting node),
and mark it as visited.

We then see an unvisited


adjacent node from S. In
this example, we have three
3
nodes but alphabetically we
choose A, mark it as visited
and enqueue it.

Next, the unvisited adjacent


4 node from S is B. We mark
it as visited and enqueue it.
Next, the unvisited adjacent
5 node from S is C. We mark
it as visited and enqueue it.

Now, S is left with no


6 unvisited adjacent nodes.
So, we dequeue and find A.

From A we have D as
unvisited adjacent node.
7
We mark it as visited and
enqueue it.

At this stage, we are left with no unmarked (unvisited) nodes. But as per the
algorithm we keep on dequeuing in order to get all unvisited nodes. When the
queue gets emptied, the program is over.

You might also like