Depth First Search or DFS for a Graph
Last Updated :
26 Nov, 2024
Depth First Search (or DFS) for a graph is similar to Depth First Traversal of a tree. Like trees, we traverse all adjacent vertices one by one. When we traverse an adjacent vertex, we completely finish the traversal of all vertices reachable through that adjacent vertex. After we finish traversing one adjacent vertex and its reachable vertices, we move to the next adjacent vertex and repeat the process. This is similar to a tree, where we first completely traverse the left subtree and then move to the right subtree. The key difference is that, unlike trees, graphs may contain cycles (a node may be visited more than once). To avoid processing a node multiple times, we use a boolean visited array.
Example:
Input: adj = [[1, 2], [0, 2], [0, 1, 3, 4], [2], [2]]

Output: 1 2 0 3 4
Explanation: The source vertex s is 1. We visit it first, then we visit an adjacent. There are two adjacent 1, 0 and 2. We can pick any of the two (
- Start at 1: Mark as visited. Output: 1
- Move to 2: Mark as visited. Output: 2
- Move to 0: Mark as visited. Output: 0 (backtrack to 2)
- Move to 3: Mark as visited. Output: 3 (backtrack to 2)
- Move to 4: Mark as visited. Output: 4 (backtrack to 1)
Input: [[2,3,1], [0], [0,4], [0], [2]]

Output: 0 2 4 3 1
Explanation: DFS Steps:
- Start at 0: Mark as visited. Output: 0
- Move to 2: Mark as visited. Output: 2
- Move to 4: Mark as visited. Output: 4 (backtrack to 2, then backtrack to 0)
- Move to 3: Mark as visited. Output: 3 (backtrack to 0)
- Move to 1: Mark as visited. Output: 1
Note that there can be multiple DFS traversals of a graph according to the order in which we pick adjacent vertices. Here we pick vertices as per the insertion order.
DFS from a Given Source of Undirected Graph:
The algorithm starts from a given source and explores all reachable vertices from the given source. It is similar to Preorder Tree Traversal where we visit the root, then recur for its children. In a graph, there maybe loops. So we use an extra visited array to make sure that we do not process a vertex again.
Let us understand the working of Depth First Search with the help of the following illustration: for the source as 0.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Recursive function for DFS traversal
void DFSRec(vector<vector<int>> &adj, vector<bool> &visited, int s){
visited[s] = true;
// Print the current vertex
cout << s << " ";
// Recursively visit all adjacent vertices
// that are not visited yet
for (int i : adj[s])
if (visited[i] == false)
DFSRec(adj, visited, i);
}
// Main DFS function that initializes the visited array
// and call DFSRec
void DFS(vector<vector<int>> &adj, int s){
vector<bool> visited(adj.size(), false);
DFSRec(adj, visited, s);
}
// To add an edge in an undirected graph
void addEdge(vector<vector<int>> &adj, int s, int t){
adj[s].push_back(t);
adj[t].push_back(s);
}
int main(){
int V = 5;
vector<vector<int>> adj(V);
// Add edges
vector<vector<int>> edges={{1, 2},{1, 0},{2, 0},{2, 3},{2, 4}};
for (auto &e : edges)
addEdge(adj, e[0], e[1]);
int s = 1; // Starting vertex for DFS
cout << "DFS from source: " << s << endl;
DFS(adj, s); // Perform DFS starting from the source vertex
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Node structure for adjacency list
struct Node {
int dest;
struct Node* next;
};
// Structure to represent an adjacency list
struct AdjList {
struct Node* head;
};
// Function to create a new adjacency list node
struct Node* createNode(int dest) {
struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// Recursive function for DFS traversal
void DFSRec(struct AdjList adj[], int visited[], int s) {
// Mark the current vertex as visited
visited[s] = 1;
// Print the current vertex
printf("%d ", s);
// Traverse all adjacent vertices that are not visited yet
struct Node* current = adj[s].head;
while (current != NULL) {
int dest = current->dest;
if (!visited[dest]) {
DFSRec(adj, visited, dest);
}
current = current->next;
}
}
// Main DFS function that initializes the visited array
// and calls DFSRec
void DFS(struct AdjList adj[], int V, int s) {
// Initialize visited array to false
int visited[5] = {0};
DFSRec(adj, visited, s);
}
// Function to add an edge to the adjacency list
void addEdge(struct AdjList adj[], int s, int t) {
// Add edge from s to t
struct Node* newNode = createNode(t);
newNode->next = adj[s].head;
adj[s].head = newNode;
// Due to undirected Graph
newNode = createNode(s);
newNode->next = adj[t].head;
adj[t].head = newNode;
}
int main() {
int V = 5;
// Create an array of adjacency lists
struct AdjList adj[V];
// Initialize each adjacency list as empty
for (int i = 0; i < V; i++) {
adj[i].head = NULL;
}
int E = 5;
// Define the edges of the graph
int edges[][2] = {{1, 2}, {1, 0}, {2, 0}, {2, 3}, {2, 4}};
// Populate the adjacency list with edges
for (int i = 0; i < E; i++) {
addEdge(adj, edges[i][0], edges[i][1]);
}
int source = 1;
printf("DFS from source: %d\n", source);
DFS(adj, V, source);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Recursive function for DFS traversal
static void DFSRec(List<List<Integer> > adj,
boolean[] visited, int s){
// Mark the current vertex as visited
visited[s] = true;
// Print the current vertex
System.out.print(s + " ");
// Recursively visit all adjacent vertices that are
// not visited yet
for (int i : adj.get(s)) {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
}
}
// Main DFS function that initializes the visited array
static void DFS(List<List<Integer> > adj, int s) {
boolean[] visited = new boolean[adj.size()];
// Call the recursive DFS function
DFSRec(adj, visited, s);
}
// Function to add an edge to the adjacency list
static void addEdge(List<List<Integer> > adj,
int s, int t){
// Add edge from vertex s to t
adj.get(s).add(t);
// Due to undirected Graph
adj.get(t).add(s);
}
public static void main(String[] args)
{
int V = 5; // Number of vertices in the graph
// Create an adjacency list for the graph
List<List<Integer> > adj = new ArrayList<>(V);
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
// Define the edges of the graph
int[][] edges = {
{ 1, 2 }, { 1, 0 }, { 2, 0 }, { 2, 3 }, { 2, 4 }
};
// Populate the adjacency list with edges
for (int[] e : edges) {
addEdge(adj, e[0], e[1]);
}
int source = 1;
System.out.println("DFS from source: " + source);
DFS(adj, source);
}
}
Python
def dfs_rec(adj, visited, s):
# Mark the current vertex as visited
visited[s] = True
# Print the current vertex
print(s, end=" ")
# Recursively visit all adjacent vertices
# that are not visited yet
for i in adj[s]:
if not visited[i]:
dfs_rec(adj, visited, i)
def dfs(adj, s):
visited = [False] * len(adj)
# Call the recursive DFS function
dfs_rec(adj, visited, s)
def add_edge(adj, s, t):
# Add edge from vertex s to t
adj[s].append(t)
# Due to undirected Graph
adj[t].append(s)
if __name__ == "__main__":
V = 5
# Create an adjacency list for the graph
adj = [[] for _ in range(V)]
# Define the edges of the graph
edges = [[1, 2], [1, 0], [2, 0], [2, 3], [2, 4]]
# Populate the adjacency list with edges
for e in edges:
add_edge(adj, e[0], e[1])
source = 1
print("DFS from source:", source)
dfs(adj, source)
C#
using System;
using System.Collections.Generic;
class GfG{
// Recursive function for DFS traversal
static void DFSRec(List<List<int>> adj, bool[] visited, int s){
// Mark the current vertex as visited
visited[s] = true;
// Print the current vertex
Console.Write(s + " ");
// Recursively visit all adjacent vertices
// that are not visited yet
foreach (int i in adj[s]){
if (!visited[i]){
DFSRec(adj, visited, i);
}
}
}
// Main DFS function that initializes the visited array
static void PerformDFS(List<List<int>> adj, int s){
bool[] visited = new bool[adj.Count];
// Call the recursive DFS function
DFSRec(adj, visited, s);
}
static void AddEdge(List<List<int>> adj, int s, int t){
adj[s].Add(t);
adj[t].Add(s);
}
static void Main(){
int V = 5;
// Create an adjacency list for the graph
List<List<int>> adj = new List<List<int>>(V);
for (int i = 0; i < V; i++){
adj.Add(new List<int>());
}
// Define the edges of the graph
int[,] edges = {
{ 1, 2 }, { 1, 0 }, { 2, 0 }, { 2, 3 }, { 2, 4 }
};
// Populate the adjacency list with edges
for (int i = 0; i < edges.GetLength(0); i++){
AddEdge(adj, edges[i, 0], edges[i, 1]);
}
int source = 1; // Starting vertex for DFS
Console.WriteLine("DFS from source: " + source);
PerformDFS(adj, source);
}
}
JavaScript
function dfsRec(adj, visited, s)
{
// Mark the current vertex as visited
visited[s] = true;
// Print the current vertex
process.stdout.write(s + " ");
// Recursively visit all adjacent vertices that are not
// visited yet
for (let i of adj[s]) {
if (!visited[i]) {
dfsRec(adj, visited, i);
}
}
}
function dfs(adj, s)
{
const visited = new Array(adj.length).fill(false);
// Call the recursive DFS function
dfsRec(adj, visited, s);
}
function addEdge(adj, s, t)
{
// Add edge from vertex s to t
adj[s].push(t);
// Due to undirected Graph
adj[t].push(s);
}
const V = 5; // Number of vertices in the graph
// Create an adjacency list for the graph
const adj = Array.from({length : V}, () => []);
// Define the edges of the graph
const edges =
[ [ 1, 2 ], [ 1, 0 ], [ 2, 0 ], [ 2, 3 ], [ 2, 4 ] ];
// Populate the adjacency list with edges
for (let e of edges) {
addEdge(adj, e[0], e[1]);
}
const source = 1;
console.log("DFS from source: " + source);
dfs(adj, source);
OutputDFS from source: 1
1 2 0 3 4
Time complexity: O(V + E), where V is the number of vertices and E is the number of edges in the graph.
Auxiliary Space: O(V + E), since an extra visited array of size V is required, And stack size for recursive calls to DFSRec function.
Please refer Complexity Analysis of Depth First Search: for details.
DFS for Complete Traversal of Disconnected Undirected Graph
The above implementation takes a source as an input and prints only those vertices that are reachable from the source and would not print all vertices in case of disconnected graph. Let us now talk about the algorithm that prints all vertices without any source and the graph maybe disconnected.
The idea is simple, instead of calling DFS for a single vertex, we call the above implemented DFS for all all non-visited vertices one by one.
C++
#include <bits/stdc++.h>
using namespace std;
void addEdge(vector<vector<int>> &adj, int s, int t){
adj[s].push_back(t);
adj[t].push_back(s);
}
// Recursive function for DFS traversal
void DFSRec(vector<vector<int>> &adj, vector<bool> &visited,int s){
// Mark the current vertex as visited
visited[s] = true;
// Print the current vertex
cout << s << " ";
// Recursively visit all adjacent vertices that are not visited yet
for (int i : adj[s])
if (visited[i] == false)
DFSRec(adj, visited, i);
}
// Main DFS function to perform DFS for the entire graph
void DFS(vector<vector<int>> &adj){
vector<bool> visited(adj.size(), false);
// Loop through all vertices to handle disconnected graph
for (int i = 0; i < adj.size(); i++){
if (visited[i] == false){
// If vertex i has not been visited,
// perform DFS from it
DFSRec(adj, visited, i);
}
}
}
int main(){
int V = 6;
// Create an adjacency list for the graph
vector<vector<int>> adj(V);
// Define the edges of the graph
vector<vector<int>> edges = {{1, 2}, {2, 0}, {0, 3}, {4, 5}};
// Populate the adjacency list with edges
for (auto &e : edges)
addEdge(adj, e[0], e[1]);
cout << "Complete DFS of the graph:" << endl;
DFS(adj);
return 0;
}
C
#include <stdio.h>
#include <stdlib.h>
// Node structure for adjacency list
struct Node {
int dest;
struct Node* next;
};
// Structure to represent an adjacency list
struct AdjList {
struct Node* head;
};
// Function to create a new adjacency list node
struct Node* createNode(int dest) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->dest = dest;
newNode->next = NULL;
return newNode;
}
// Function to add an edge to the adjacency list
void addEdge(struct AdjList adj[], int s, int t) {
// Add edge from s to t
struct Node* newNode = createNode(t);
newNode->next = adj[s].head;
adj[s].head = newNode;
// Add edge from t to s (for undirected graph)
newNode = createNode(s);
newNode->next = adj[t].head;
adj[t].head = newNode;
}
// Recursive function for DFS traversal
void DFSRec(struct AdjList adj[], int visited[], int s) {
// Mark the current vertex as visited
visited[s] = 1;
// Print the current vertex
printf("%d ", s);
// Traverse all adjacent vertices that are not visited yet
struct Node* current = adj[s].head;
while (current != NULL) {
int dest = current->dest;
if (!visited[dest]) {
DFSRec(adj, visited, dest);
}
current = current->next;
}
}
// Main DFS function to perform DFS for the entire graph
void DFS(struct AdjList adj[], int V) {
int visited[6] = {0}; // Initialize visited array to false
// Loop through all vertices to handle disconnected graph
for (int i = 0; i < V; i++) {
if (visited[i] == 0) {
// If vertex i has not been visited,
// perform DFS from it
DFSRec(adj, visited, i);
}
}
}
int main() {
int V = 6;
// Create an array of adjacency lists
struct AdjList adj[V];
// Initialize each adjacency list as empty
for (int i = 0; i < V; i++) {
adj[i].head = NULL;
}
const int E = 4;
// Define the edges of the graph
int edges[][2] = {{1, 2}, {2, 0}, {0, 3}, {4, 5}};
// Populate the adjacency list with edges
for (int i = 0; i < E; i++) {
addEdge(adj, edges[i][0], edges[i][1]);
}
printf("Complete DFS of the graph:\n");
DFS(adj, V);
return 0;
}
Java
import java.util.ArrayList;
import java.util.List;
class GfG {
// Function to add an edge to the adjacency list
static void addEdge(List<List<Integer> > adj, int s,
int t){
adj.get(s).add(t);
adj.get(t).add(s);
}
// Recursive function for DFS traversal
static void DFSRec(List<List<Integer> > adj,
boolean[] visited, int s){
visited[s] = true;
System.out.print(s + " ");
// Recursively visit all adjacent vertices that are
// not visited yet
for (int i : adj.get(s)) {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
}
}
// Main DFS function to perform DFS for the entire graph
static void DFS(List<List<Integer> > adj, int V){
boolean[] visited = new boolean[V];
// Loop through all vertices to handle disconnected
// graph
for (int i = 0; i < V; i++) {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
}
}
public static void main(String[] args){
int V = 6;
// Create an adjacency list for the graph
List<List<Integer> > adj = new ArrayList<>();
for (int i = 0; i < V; i++) {
adj.add(new ArrayList<>());
}
// Define the edges of the graph
int[][] edges
= { { 1, 2 }, { 2, 0 }, { 0, 3 }, { 4, 5 } };
// Populate the adjacency list with edges
for (int[] edge : edges) {
addEdge(adj, edge[0], edge[1]);
}
System.out.println("Complete DFS of the graph:");
DFS(adj, V);
}
}
Python
class Graph:
def __init__(self, vertices):
# Adjacency list
self.adj = [[] for _ in range(vertices)]
def add_edge(self, s, t):
self.adj[s].append(t)
self.adj[t].append(s)
def dfs_rec(self, visited, s):
visited[s] = True
print(s, end=" ")
# Recursively visit all adjacent vertices
# that are not visited yet
for i in self.adj[s]:
if not visited[i]:
self.dfs_rec(visited, i)
def dfs(self):
visited = [False] * len(self.adj)
# Loop through all vertices to handle disconnected
# graph
for i in range(len(self.adj)):
if not visited[i]:
# Perform DFS from unvisited vertex
self.dfs_rec(visited, i)
if __name__ == "__main__":
V = 6 # Number of vertices
graph = Graph(V)
# Define the edges of the graph
edges = [(1, 2), (2, 0), (0, 3), (4, 5)]
# Populate the adjacency list with edges
for edge in edges:
graph.add_edge(edge[0], edge[1])
print("Complete DFS of the graph:")
graph.dfs() # Perform DFS
C#
using System;
using System.Collections.Generic;
class Program
{
// Function to add an edge to the adjacency list
static void AddEdge(List<List<int>> adj, (int, int) edge)
{
adj[edge.Item1].Add(edge.Item2);
adj[edge.Item2].Add(edge.Item1);
}
// Recursive function for DFS traversal
static void DFSRec(List<List<int>> adj, bool[] visited, int s){
// Mark the current vertex as visited
visited[s] = true;
// Print the current vertex
Console.Write(s + " ");
// Recursively visit all adjacent vertices
// that are not visited yet
foreach (int i in adj[s]){
if (!visited[i]){
DFSRec(adj, visited, i); // Recursive call
}
}
}
// Main DFS function to perform DFS for the entire graph
static void DFS(List<List<int>> adj){
bool[] visited = new bool[adj.Count];
// Loop through all vertices to handle
// disconnected graph
for (int i = 0; i < adj.Count; i++){
if (!visited[i]){
// If vertex i has not been visited,
// perform DFS from it
DFSRec(adj, visited, i);
}
}
}
static void Main(){
int V = 6;
// Create an adjacency list for the graph
var adj = new List<List<int>>(new List<int>[V]);
for (int i = 0; i < V; i++){
adj[i] = new List<int>(); // Initialize each list
}
// Define the edges of the graph using tuples
var edges = new List<(int, int)>{(1, 2),(2, 0),(0, 3),(4, 5)};
// Populate the adjacency list with edges
foreach (var edge in edges)
{
AddEdge(adj, edge);
}
Console.WriteLine("Complete DFS of the graph:");
DFS(adj);
}
}
JavaScript
function addEdge(adj, s, t){
adj[s].push(t);
adj[t].push(s);
}
// Recursive function for DFS traversal
function DFSRec(adj, visited, s)
{
visited[s] = true;
console.log(s + " ");
// Recursively visit all adjacent vertices that are not
// visited yet
adj[s].forEach(i => {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
});
}
// Main DFS function to perform DFS for the entire graph
function DFS(adj, V)
{
let visited = new Array(V).fill(false);
// Loop through all vertices to handle disconnected
// graph
for (let i = 0; i < V; i++) {
if (!visited[i]) {
DFSRec(adj, visited, i);
}
}
}
// Driver code
let V = 6;
// Create an adjacency list for the graph
let adj = new Array(V);
for (let i = 0; i < V; i++) {
adj[i] = [];
}
// Define the edges of the graph
let edges = [ [ 1, 2 ], [ 2, 0 ], [ 0, 3 ], [ 4, 5 ] ];
// Populate the adjacency list with edges
edges.forEach(edge => { addEdge(adj, edge[0], edge[1]); });
console.log("Complete DFS of the graph:");
DFS(adj, V);
OutputComplete DFS of the graph:
0 2 1 3 4 5
Time complexity: O(V + E). Note that the time complexity is same here because we visit every vertex at most once and every edge is traversed at most once (in directed) and twice in undirected.
Auxiliary Space: O(V + E), since an extra visited array of size V is required, And stack size for recursive calls to DFSRec function.
Related Articles: