If you want to practice data structure and algorithm programs, you can go through 100+ java coding interview questions.
Table of Contents [hide]
Graph traversal Algorithms
In 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
Let see with the help of example:

We start with node 40. It then visits 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
Java DFS Example
There are two ways to represent a graph.
-
- Using Neighbours list
- Using Adjacency Matrix
Using Neighbours list
In this, you can have List<Node> as neighbours in Node class as below.
Here is the complete java program for DFS implementation for iterative as well as recursive method.
When you run above program, you will get below output
Using Adjacency Matrix
Adjacency_matrix is used to find the connection between two nodes.
if adjacency_matrix[i][j]==1, then nodes at index i and index j are connected
Below diagram will help you to understand adjacency matrix.
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.
oh, so easy to understand, thanks!