Depth First Search in java

Last updated on March 14th, 2017 at 12:48 pm

Previous
Next

If you want to practice data structure and algorithm programs, you can go through data structure and algorithm interview questions.

In previous post, we have seen breadth first search(bfs). In this post, we will see how to implement depth first search(DFS) in java.

Graph traversal Algorithms:

Breadth first search in javaDepth first search in javaIn DFS,  You start with  an un-visited node and start picking an adjacent node, until you have no choice, then you backtrack until you have another choice to pick a node, if not, you select another un-visited node.

DFS can be implemented in two ways.

  • Recursive
  • Iterative

Iterative:

Depth first search can be implemented using iterative approach.
Let see with the help of example:

Depth first search example
We start with node 40. It then visit node 20, node 50, node 70 respectively as they are directly connected . After that , it backtracks to node 20 and visited node 60,node 30 and node 10 respectively.

Recursive:

Depth first search can be implemented using recursion too. We do not need to maintain external stack, it will be taken care by recursion.

Java Example:

Create DepthFirstSearchExample.java

When you run above program, you will get below output

Please go through data structure and algorithm interview programs for more such programs.

Previous
Next

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.

Add Comment

Join Our News Letter - Stay Updated

Subscribe to Awesome Java Content.
You can like our facebook page Java2blog