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

Depth-first search can be implemented using iterative approach.
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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

// Iterative DFS using stack

publicvoiddfsUsingStack(Node node)

{

Stack<Node>stack=newStack<Node>();

stack.add(node);

node.visited=true;

while(!stack.isEmpty())

{

Node element=stack.pop();

System.out.print(element.data+" ");

List<Node>neighbours=element.getNeighbours();

for(inti=0;i<neighbours.size();i++){

Noden=neighbours.get(i);

if(n!=null&&!n.visited)

{

stack.add(n);

n.visited=true;

}

}

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

// Recursive DFS

publicvoiddfs(Node node)

{

System.out.print(node.data+" ");

List neighbours=node.getNeighbours();

node.visited=true;

for(inti=0;i<neighbours.size();i++){

Noden=neighbours.get(i);

if(n!=null&&!n.visited)

{

dfs(n);

}

}

}

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.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

staticclassNode

{

intdata;

booleanvisited;

List<Node>neighbours;

Node(intdata)

{

this.data=data;

this.neighbours=newArrayList<>();

}

publicvoidaddneighbours(Node neighbourNode)

{

this.neighbours.add(neighbourNode);

}

publicList getNeighbours(){

returnneighbours;

}

publicvoidsetNeighbours(List neighbours){

this.neighbours=neighbours;

}

}

Here is the complete java program for DFS implementation for iterative as well as recursive method.