Flat Preloader Icon

Graph Traversing

Overview

  1. Traversing Graph
  2. BFS
  3. Logic for BFS
  4. Example
  5. DFS
  6. Logic for DFS
  7. Example

Traversing

There are two standard way of
traversing a graph

  • BFS Breadth first search
  • DFS Depth First Search

BFS

  1. Traversing graph has only issue that graph may have cycle. You may revisit a node .
  2. To avoid processing a node more than once , we divide the vertices into two categories :
  •  visited
  • Not visited
  1. A boolean visited array is used to mark the visited vertices
  2. BFs ( Breadth First Search) uses a queue
    data structure for traversal .
  3. Traversing begin from a node called source node

Logic for BFS

				
					BFS (G,S)
let Q be the queue
Q.insert(s);
v[s]=true;
while(!Q.is empty())
{
n=Q.getfront();
Q.del();
for all the neighbour u of n
   if v[u]==false
      Q.insert(u);
      v[u]=true;
}
				
			

Example:

DFS

DFS is Depth first search.The main defferenee between BFS and DFS is that the DFS uses stuck in place of Queue

Logic for DFS

				
					BFS (G,S)
let stack be the queue
stack.push(s);
v[s]=true;
while(!stack.is empty())
{
n=stack.getfront();
stack.pop();
for all the neighbour u of n
   if v[u]==false
      stack.insert(u);
      v[u]=true;
}
				
			

Example