**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**:

- We will modify the DFS approach used here.
- Maintain a visited [] to keep track of already visited vertices to avoid loops.
- 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.
- 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 DisconnetedGraphDFS { | |

//this code will work for disconnected graphs as well | |

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 DFSRecursion(){ | |

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

System.out.println("Depth-First Search: "); | |

//visit from each node if not already visited | |

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

if(!visited[i]){ | |

dfs(i, 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 vertex = adjList[start].get(i); | |

if(!visited[vertex]) | |

dfs(vertex,visited); | |

} | |

} | |

} | |

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

int vertices = 7; | |

Graph graph = new Graph(vertices); | |

graph.addEgde(1,3); | |

graph.addEgde(2,3); | |

graph.addEgde(0,4); | |

graph.addEgde(4,5); | |

graph.addEgde(5,6); | |

graph.DFSRecursion(); | |

} | |

} |

**Output:**

Depth-First Search:

0 4 5 6 1 3 2