 Explore
Free Resources
Comprehensive Courses
Company-Specific Courses Edit Edit

# Depth First Traversal or DFS

Published on 07 Mar 2020

When a graph is traversed by visiting the nodes in the forward (deeper) direction as long as possible, the traversal is called depth-first traversal. For example, for the graph shown in below figure, the depth-first traversal starting at the vertex 0 visits the node in the orders:

i. 0 1 2 6 7 8 5 3 4

ii. 0 4 3 5 8 6 7 2 1 Depth First Traversal for a graph is similar to Depth First Traversal of a tree. The only catch here is, unlike trees, graphs may contain cycles, so we may come to the same node again. To avoid processing a node more than once, we use a boolean visited array.

Following are implementations of simple Depth First Traversal. The C++ implementation uses adjacency list representation of graphs. STL‘s list container is used to store lists of adjacent nodes.

## C++

// C++ program to print DFS traversal from
// a given vertex in a  given graph
#include<iostream>
#include<list>
using namespace std;

// Graph class represents a directed graph
class Graph
{
int V;    // No. of vertices

// Pointer to an array containing

// A recursive function used by DFS
void DFSUtil(int v, bool visited[]);
public:
Graph(int V);   // Constructor

// function to add an edge to graph

// DFS traversal of the vertices
// reachable from v
void DFS(int v);
};

Graph::Graph(int V)
{
this->V = V;
}

{
}

void Graph::DFSUtil(int v, bool visited[])
{
// Mark the current node as visited and
// print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent
// to this vertex
list<int>::iterator i;
if (!visited[*i])
DFSUtil(*i, visited);
}

// DFS traversal of the vertices reachable from v.
// It uses recursive DFSUtil()
void Graph::DFS(int v)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// Call the recursive helper function
// to print DFS traversal
DFSUtil(v, visited);
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);

cout << "Following is Depth First Traversal"
" (starting from vertex 2) \n";
g.DFS(2);

return 0;
}


## Java

// Java program to print DFS traversal from a given given graph
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list
// representation
class Graph
{
private int V;   // No. of vertices

// Array  of lists for Adjacency List Representation

// Constructor
Graph(int v)
{
V = v;
for (int i=0; i<v; ++i)
}

//Function to add an edge into the graphvoid addEdge(int v, int w)
{
}

// A function used by DFSvoid DFSUtil(int v,boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v+" ");

// Recur for all the vertices adjacent to this vertex
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n, visited);
}
}

// The function to do DFS traversal. It uses recursive DFSUtil()void DFS(int v)
{
// Mark all the vertices as not visited(set as// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper function to print DFS traversal
DFSUtil(v, visited);
}

public static void main(String args[])
{
Graph g = new Graph(4);

System.out.println("Following is Depth First Traversal "+
"(starting from vertex 2)");

g.DFS(2);
}
}


## Python

# Python program to print DFS traversal from a
# given given graph
from collections import defaultdict

# This class represents a directed graph using
class Graph:

# Constructordef __init__(self):

# default dictionary to store graphself.graph = defaultdict(list)

self.graph[u].append(v)

# A function used by DFSdef DFSUtil(self,v,visited):

# Mark the current node as visited and print it
visited[v]= Trueprint v,

# Recur for all the vertices adjacent to this vertexfor i in self.graph[v]:if visited[i] == False:self.DFSUtil(i, visited)

# The function to do DFS traversal. It uses# recursive DFSUtil()def DFS(self,v):

# Mark all the vertices as not visited
visited = [False]*(len(self.graph))

# Call the recursive helper function to print# DFS traversalself.DFSUtil(v,visited)

# Driver code
# Create a graph given in the above diagram
g = Graph()

print "Following is DFS from (starting from vertex 2)"
g.DFS(2)


Output:

Following is Depth First Traversal (starting from vertex 2)
2 0 1 3


How to handle disconnected graph?

The above code traverses only the vertices reachable from a given source vertex. All the vertices may not be reachable from a given vertex (example Disconnected graph). To do complete DFS traversal of such graphs, we must call DFSUtil() for every vertex. Also, before calling DFSUtil(), we should check if it is already printed by some other call of DFSUtil(). Following implementation does the complete graph traversal even if the nodes are unreachable. The differences from the above code are highlighted in the below code.

## C++

// C++ program to print DFS traversal for a given given graph
#include<iostream>
#include         <list>
using namespace std;

class Graph
{
int V;    // No. of vertices
void DFSUtil(int v, bool visited[]);  // A function used by DFS
public:
Graph(int V);   // Constructor
void addEdge(int v, int w);   // function to add an edge to graph
void DFS();    // prints DFS traversal of the complete graph
};

Graph::Graph(int V)
{
this->V = V;
}

{
}

void Graph::DFSUtil(int v, bool visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
cout << v << " ";

// Recur for all the vertices adjacent to this vertex
list<int>::iterator i;
if(!visited[*i])
DFSUtil(*i, visited);
}

// The function to do DFS traversal. It uses recursive DFSUtil()
void Graph::DFS()
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for (int i = 0; i < V; i++)
visited[i] = false;

// Call the recursive helper function to print DFS traversal
// starting from all vertices one by one
for (int i = 0; i < V; i++)
if (visited[i] == false)
DFSUtil(i, visited);
}

int main()
{
// Create a graph given in the above diagram
Graph g(4);

cout << "Following is Depth First Traversaln";
g.DFS();

return 0;
}


## Java

// Java program to print DFS traversal from a given given graph
import java.io.*;
import java.util.*;

// This class represents a directed graph using adjacency list
// representation
class Graph
{
private int V;   // No. of vertices

// Array  of lists for Adjacency List Representation

// Constructor
Graph(int v)
{
V = v;
for (int i=0; i<v; ++i)
}

//Function to add an edge into the graphvoid addEdge(int v, int w)
{
}

// A function used by DFSvoid DFSUtil(int v,boolean visited[])
{
// Mark the current node as visited and print it
visited[v] = true;
System.out.print(v+" ");

// Recur for all the vertices adjacent to this vertex
while (i.hasNext())
{
int n = i.next();
if (!visited[n])
DFSUtil(n,visited);
}
}

// The function to do DFS traversal. It uses recursive DFSUtil()void DFS()
{
// Mark all the vertices as not visited(set as// false by default in java)
boolean visited[] = new boolean[V];

// Call the recursive helper function to print DFS traversal// starting from all vertices one by onefor (int i=0; i<V; ++i)if (visited[i] == false)
DFSUtil(i, visited);
}

public static void main(String args[])
{
Graph g = new Graph(4);

System.out.println("Following is Depth First Traversal");

g.DFS();
}
}


## Python

# Python program to print DFS traversal for complete graph
from collections import defaultdict

# This class represents a directed graph using adjacency
# list representation
class Graph:

# Constructordef __init__(self):

# default dictionary to store graphself.graph = defaultdict(list)

self.graph[u].append(v)

# A function used by DFSdef DFSUtil(self, v, visited):

# Mark the current node as visited and print it
visited[v]= Trueprint v,

# Recur for all the vertices adjacent to# this vertexfor i in self.graph[v]:if visited[i] == False:self.DFSUtil(i, visited)

# The function to do DFS traversal. It uses# recursive DFSUtil()def DFS(self):
V = len(self.graph)  #total vertices

# Mark all the vertices as not visited
visited =[False]*(V)

# Call the recursive helper function to print# DFS traversal starting from all vertices one# by onefor i in range(V):if visited[i] == False:self.DFSUtil(i, visited)

# Driver code
# Create a graph given in the above diagram
g = Graph()

print "Following is Depth First Traversal"
g.DFS()


Output:

Following is Depth First Traversal0 1 2 3


Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of edges in the graph.  