Graph’s In Depth [PART 2]

In this article, we will discuss popular graph traversal algorithms. Before proceeding please read this article at first to get clear idea about graphs.

Graph Traversals

  • BFS (Breadth First Search)
  • DFS (Depth First Search)

Breadth First Search

In the Breadth First Search, the traversal is done in a level wise manner.

BFS uses Queue data structure for its implementation.

The Algorithm for BFS is as follows:

  VISIT[]   //initialize VISIT ARRAY to 0
  QUEUE     //initialize queue
  for each v in LIST{
 if(QUEUE.isEmpty()) return;
 x=delete from QUEUE;
 current=x;  //assign to current;

Explaination Of Algorithm

BFS(vertex) accepts the starting vertex in the graph.

In line , VISIT[] & QUEUE is data structure to implement the BFS on graph.

VISIT[] -> is the array which represents whether the vertex has been visited or not

QUEUE -> is the data structure which stores the vertex.

We have assigned the starting vertex to variable current & on line , we have marked it visited.

Now , LIST[] array stores the list of vertices which are adjacent to current;

The for loop runs for every vertex in the LIST[] array.

If condition is cheking if the vertex is already visited,if it is not already visited,

we add that vertex in the QUEUE and mark it visited.

At last , we check is the QUEUE is EMPTY , if not Delete an element from QUEUE & assign it to current.

Just repeat the above procedure till , QUEUE is EMPTY.


Depth First Search is a popular method for systematically traversing the vertices of graph.

In Depth First Search, We consider a vertex , and explore it ,until all the adjacent vertices are visited.

DFS uses stack for the implementation.

During the execution of DFS algorithm, each node of the graph will be in one of the three states indicating the visiting status of the node as follows:

  • flag=1 for ready state : initial state of node
  • flag=2 for waiting state : node is waiting in the stack for processing
  • flag=3 for processed state: node has been processed.

The algorithm for DFS is as follows;

flag=1 for all nodes
flag=2 for node v1
while(stack is not empty){
   flag=3 for node x
   for all y, adjacent to x
   if(flag==1_ for y then
     flag=2 for y

In the next article , we will implement graph data structure in java & perform the above traversals on the graph.

Thanks for reading !

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.