Depth First Search or DFS on Directed Graph
Last Updated :
23 Jul, 2025
Depth-First Search (DFS) is a basic algorithm used to explore graph structures. In directed graphs, DFS can start from a specific point and explore all the connected nodes. It can also be used to make sure every part of the graph is visited, even if the graph has disconnected sections. This article explains how DFS works when starting from a single point and how it can be used to explore an entire graph, including disconnected parts.
Example:
Input: V = 5, E = 5, edges = {{1, 2}, {1, 0}, {2, 0}, {2, 3}, {4, 2}}, source = 1
Output: 1 2 0 3
Explanation: DFS Steps:
- 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)
- All neighbors of 2 explored (backtrack to 1)
- All neighbors of 1 explored (end of traversal)
Input: V = 5, E = 4, edges = {{0, 2}, {0, 3}, {2, 4}, {1, 0}}, source = 2
Output: 2 4
Explanation: DFS Steps:
- Start at 2: Mark as visited. Output: 2
- Move to 4: Mark as visited. Output: 4 (backtrack to 2)
- All neighbors of 2 explored (backtrack to start)
DFS from a Given Source in Directed Graph
Depth-First Search (DFS) from a given source is a method of exploring a directed graph by starting at a specific vertex and traversing each node as far as we can go down in the path. If we reach a vertex that has no unvisited neighbors, we backtrack to the previous vertex to explore any other paths that haven't been visited yet. This approach is particularly useful for tasks such as finding paths, checking connectivity, and exploring all reachable nodes from a starting point.
How It Works:
- Keep a boolean visited array to keep track of which vertices have already been visited. This will help in not entering in infinite loops when there are cycles in the graph.
- Use Recursion to visited all unvisited neighbours of source node:
- First marks the current vertex as visited and processes the current vertex (for example, by printing its value).
- Then, recursively visits each unvisited neighbor of the current vertex.
- If a vertex has no unvisited neighbors, backtracks to the previous vertex to explore other unvisited paths.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
// Function to add an edge to the adjacency list
void addEdge(vector<vector<int>> &adj, int s, int t){
// Add edge from vertex s to t
adj[s].push_back(t);
}
// 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 that initializes the visited array
// and call DFSRec
void DFS(vector<vector<int>> &adj, int s){
vector<bool> visited(adj.size(), false);
// Call the recursive DFS function
DFSRec(adj, visited, s);
}
int main(){
int V = 5;
// Create an adjacency list for the graph
vector<vector<int>> adj(V);
// Define the edges of the graph
vector<vector<int>> edges={{1, 2}, {1, 0}, {2, 0}, {2, 3}, {4, 2}};
// Populate the adjacency list with edges
for (auto &e : edges)
addEdge(adj, e[0], e[1]);
int source = 1;
cout << "DFS from source: " << source << endl;
DFS(adj, source);
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;
}
// 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);
}
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 {
// 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);
}
// 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);
}
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 add_edge(adj, s, t):
# Add edge from vertex s to t
adj[s].append(t)
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)
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{
static void AddEdge(List<List<int>> adj, int s, int t){
adj[s].Add(t);
}
// 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 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 addEdge(adj, s, t){
// Add edge from vertex s to t
adj[s].push(t);
}
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);
}
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 Directed Graphs
In a directed graph, edges have a specific direction means we can travel from one vertex to another only in the direction the edge points. A disconnected graph is one in which not all vertices are reachable from a single vertex.
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.
To handle such a graph in DFS, we must ensure that the DFS algorithm starts from every unvisited vertex and this results in covering all components of the graph
C++
#include <bits/stdc++.h>
using namespace std;
void addEdge(vector<vector<int>> &adj, int s, int t){
adj[s].push_back(t);
}
// 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;
}
// 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);
}
// 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)
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);
}
// 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);
}
// 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.
Similar Reads
Basics & Prerequisites
Data Structures
Array Data StructureIn this article, we introduce array, implementation in different popular languages, its basic operations and commonly seen problems / interview questions. An array stores items (in case of C/C++ and Java Primitive Arrays) or their references (in case of Python, JS, Java Non-Primitive) at contiguous
3 min read
String in Data StructureA string is a sequence of characters. The following facts make string an interesting data structure.Small set of elements. Unlike normal array, strings typically have smaller set of items. For example, lowercase English alphabet has only 26 characters. ASCII has only 256 characters.Strings are immut
2 min read
Hashing in Data StructureHashing is a technique used in data structures that efficiently stores and retrieves data in a way that allows for quick access. Hashing involves mapping data to a specific index in a hash table (an array of items) using a hash function. It enables fast retrieval of information based on its key. The
2 min read
Linked List Data StructureA linked list is a fundamental data structure in computer science. It mainly allows efficient insertion and deletion operations compared to arrays. Like arrays, it is also used to implement other data structures like stack, queue and deque. Hereâs the comparison of Linked List vs Arrays Linked List:
2 min read
Stack Data StructureA Stack is a linear data structure that follows a particular order in which the operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). LIFO implies that the element that is inserted last, comes out first and FILO implies that the element that is inserted first
2 min read
Queue Data StructureA Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
2 min read
Tree Data StructureTree Data Structure is a non-linear data structure in which a collection of elements known as nodes are connected to each other via edges such that there exists exactly one path between any two nodes. Types of TreeBinary Tree : Every node has at most two childrenTernary Tree : Every node has at most
4 min read
Graph Data StructureGraph Data Structure is a collection of nodes connected by edges. It's used to represent relationships between different entities. If you are looking for topic-wise list of problems on different topics like DFS, BFS, Topological Sort, Shortest Path, etc., please refer to Graph Algorithms. Basics of
3 min read
Trie Data StructureThe Trie data structure is a tree-like structure used for storing a dynamic set of strings. It allows for efficient retrieval and storage of keys, making it highly effective in handling large datasets. Trie supports operations such as insertion, search, deletion of keys, and prefix searches. In this
15+ min read
Algorithms
Searching AlgorithmsSearching algorithms are essential tools in computer science used to locate specific items within a collection of data. In this tutorial, we are mainly going to focus upon searching in an array. When we search an item in an array, there are two most common algorithms used based on the type of input
2 min read
Sorting AlgorithmsA Sorting Algorithm is used to rearrange a given array or list of elements in an order. For example, a given array [10, 20, 5, 2] becomes [2, 5, 10, 20] after sorting in increasing order and becomes [20, 10, 5, 2] after sorting in decreasing order. There exist different sorting algorithms for differ
3 min read
Introduction to RecursionThe process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called a recursive function. A recursive algorithm takes one step toward solution and then recursively call itself to further move. The algorithm stops once we reach the solution
14 min read
Greedy AlgorithmsGreedy algorithms are a class of algorithms that make locally optimal choices at each step with the hope of finding a global optimum solution. At every step of the algorithm, we make a choice that looks the best at the moment. To make the choice, we sometimes sort the array so that we can always get
3 min read
Graph AlgorithmsGraph is a non-linear data structure like tree data structure. The limitation of tree is, it can only represent hierarchical data. For situations where nodes or vertices are randomly connected with each other other, we use Graph. Example situations where we use graph data structure are, a social net
3 min read
Dynamic Programming or DPDynamic Programming is an algorithmic technique with the following properties.It is mainly an optimization over plain recursion. Wherever we see a recursive solution that has repeated calls for the same inputs, we can optimize it using Dynamic Programming. The idea is to simply store the results of
3 min read
Bitwise AlgorithmsBitwise algorithms in Data Structures and Algorithms (DSA) involve manipulating individual bits of binary representations of numbers to perform operations efficiently. These algorithms utilize bitwise operators like AND, OR, XOR, NOT, Left Shift, and Right Shift.BasicsIntroduction to Bitwise Algorit
4 min read
Advanced
Segment TreeSegment Tree is a data structure that allows efficient querying and updating of intervals or segments of an array. It is particularly useful for problems involving range queries, such as finding the sum, minimum, maximum, or any other operation over a specific range of elements in an array. The tree
3 min read
Pattern SearchingPattern searching algorithms are essential tools in computer science and data processing. These algorithms are designed to efficiently find a particular pattern within a larger set of data. Patten SearchingImportant Pattern Searching Algorithms:Naive String Matching : A Simple Algorithm that works i
2 min read
GeometryGeometry is a branch of mathematics that studies the properties, measurements, and relationships of points, lines, angles, surfaces, and solids. From basic lines and angles to complex structures, it helps us understand the world around us.Geometry for Students and BeginnersThis section covers key br
2 min read
Interview Preparation
Practice Problem