This post is completed by 2 users

  • 1
Add to List
Beginner

267. Graph – Depth First Search using Recursion

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:

  1. Maintain a visited [] to keep track of already visited vertices to avoid loops.
  2. 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.
  3. See the code for more understanding.

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

Output:

0 2 3 4 5 1