This post is completed by 1 user

  • 1
Add to List
Medium

269. Graph – Depth First Search in Disconnected Graph

Objective: Given a Graph in which one or more vertices are disconnected, do the depth first traversal.

Earlier we have seen DFS where all the vertices in graph were connected. In this article we will see how to do DFS if graph is disconnected.

Example:

Approach:

  1. We will modify the DFS approach used here.
  2. Maintain a visited [] to keep track of already visited vertices to avoid loops.
  3. Iterate through all the vertices and for each vertex, 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.
  4. See the code for more understanding.

Output:

Depth-First Search:

0 4 5 6 1 3 2