Open In App

Depth First Search or DFS on Directed Graph

Last Updated : 23 Jul, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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

3

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

4

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);

Output
DFS 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);

Output
Complete 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.


Article Tags :
Practice Tags :

Similar Reads