Breadth First Search & Depth First Search Examples with steps

1) Breadth First Search :

  • A) Declare a queue and insert the starting vertex. 

 

  • B) Initialize a visited array and mark the starting vertex as visited. 

 

  • C) Follow the below process till the queue becomes empty: 

    • 1) Remove the first vertex of the queue. 

    • 2) Mark that vertex as visited. 

    • 3) Insert all the unvisited neighbours of the vertex into the queue. 






2) Depth First Search :

The step by step process to implement the DFS traversal is given as follows - 

 

  1. 1) First, create a stack with the total number of vertices in the graph. 

  2. 2) Now, choose any vertex as the starting point of traversal, and push that vertex into the stack. 

  3. 3) After that, push a non-visited vertex (adjacent to the vertex on the top of the stack) to the top of the stack. 

  4. 4) Now, repeat steps 3 and 4 until no vertices are left to visit from the vertex on the stack's top. 

  5. 5) If no vertex is left, go back and pop a vertex from the stack. 

  6. 6) Repeat steps 2, 3, and 4 until the stack is empty. 


                                     







Post a Comment

Previous Post Next Post