**Objective**: Given a graph, do the depth first traversal using recursion.

Earlier we have seen DFS using stack. In this article we will see how to do DFS using recursion. (Recursion also uses stack internally so more or less it’s same)

**What is depth-first traversal**– Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking. Source – Wiki

**Example**:

**Approach:**

- Maintain a visited [] to keep track of already visited vertices to avoid loops.
- Start from the source vertex and make a recursive call to all the vertices which can be visited from the source and in recursive call, all these vertices will act a source.
- See the code for more understanding.

**Time Complexity**: O(V+E) V – no of vertices, E – no of edges

**Code:**

This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.

Learn more about bidirectional Unicode characters

import java.util.LinkedList; | |

public class GraphDFSRecursion { | |

static class Graph{ | |

int vertices; | |

LinkedList<Integer>[] adjList; | |

Graph(int vertices){ | |

this.vertices = vertices; | |

adjList = new LinkedList[vertices]; | |

for (int i = 0; i <vertices ; i++) { | |

adjList[i] = new LinkedList<>(); | |

} | |

} | |

public void addEgde(int source, int destination){ | |

adjList[source].addFirst(destination); | |

} | |

public void printGraph(){ | |

for (int i = 0; i <vertices ; i++) { | |

if(adjList[i].size()>0) { | |

System.out.println("Vertex " + i + " is connected to: "); | |

for (int j = 0; j < adjList[i].size(); j++) { | |

System.out.print(adjList[i].get(j) + " "); | |

} | |

System.out.println(); | |

} | |

} | |

} | |

public void DFSRecursion(int startVertex){ | |

boolean [] visited = new boolean[vertices]; | |

dfs(startVertex, visited); | |

} | |

public void dfs(int start, boolean [] visited){ | |

visited[start] = true; | |

System.out.print(start + " "); | |

for (int i = 0; i <adjList[start].size() ; i++) { | |

int destination = adjList[start].get(i); | |

if(!visited[destination]) | |

dfs(destination,visited); | |

} | |

} | |

} | |

public static void main(String[] args) { | |

int vertices = 6; | |

Graph graph = new Graph(vertices); | |

graph.addEgde(0, 1); | |

graph.addEgde(0, 2); | |

graph.addEgde(1, 2); | |

graph.addEgde(1, 3); | |

graph.addEgde(3, 4); | |

graph.addEgde(2, 3); | |

graph.addEgde(4, 0); | |

graph.addEgde(4, 1); | |

graph.addEgde(4, 5); | |

graph.DFSRecursion(0); | |

} | |

} |

**Output:**

0 2 3 4 5 1