The Wayback Machine - https://web.archive.org/web/20240921060229/https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/
Open In App

Depth First Search or DFS for a Graph

Last Updated : 12 Aug, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow
Companies:
Show Topics
Solve Problem
Easy
63.07%
2.8L

Depth First Traversal (or DFS) for a graph is similar to Depth First Traversal of a tree. The only catch here is, that, unlike trees, graphs may contain cycles (a node may be visited twice). To avoid processing a node more than once, use a boolean visited array. A graph can have more than one DFS traversal.

Example:

Input: V = 5, E = 5, edges = {{1, 2}, {1, 0}, {0, 2}, {2, 3}, {2, 4}}, source = 1

Input_undirected_Graph

Output: 1 2 0 3 4
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)
  • Move to 4: Mark as visited. Output: 4 (backtrack to 1)

Input: V = 5, E = 4, edges = {{0, 2}, {0, 3}, {0, 1}, {2, 4}}, source = 0

Input_undirected_Graph2

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

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.

The core understanding of algorithms such as Depth First Search or DFS are very important and also frequently asked in Technical exams and interview to have the strong knowledge of these concept you should check out our course Tech Interview 101 – From DSA to System Design in which you get the basic to advance knowledge of the data structure and algorithms .

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); 
    // Due to undirected Graph
    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 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; // Number of vertices in the graph

    // 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},{2, 4}};

    // Populate the adjacency list with edges
    for (auto &e : edges)
        addEdge(adj, e[0], e[1]);

    int source = 1; // Starting vertex for DFS
    cout << "DFS from source: " << source << endl;
    DFS(adj, source); // 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;
}

// 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;
}

// 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);
        // Due to undirected Graph
        adj.get(t).add(s);
    }

    // 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)
    # Due to undirected Graph
    adj[t].append(s)


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);
        adj[t].Add(s);
    }

    // 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);
    // Due to undirected Graph
    adj[t].push(s);
}

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

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.

Related Articles:



Similar Reads

Depth First Search or DFS for disconnected Graph
Given a Disconnected Graph, the task is to implement DFS or Depth First Search Algorithm for this Disconnected Graph. Example: Input: Output: 0 1 2 3 Algorithm for DFS on Disconnected Graph:In the post for Depth First Search for Graph, only the vertices reachable from a given source vertex can be visited. All the vertices may not be reachable from
7 min read
Depth First Search or DFS on Directed Graph
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
15+ min read
Top 10 Interview Questions on Depth First Search (DFS)
Depth-first search (DFS) is an algorithm for traversing or searching tree or graph data structures. One starts at the root (selecting some arbitrary node as the root in the case of a graph) and explores as far as possible along each branch before backtracking. Here are some important DFS problems asked in Technical Interviews: Find number of island
1 min read
Time and Space Complexity of Depth First Search (DFS)
The time complexity of Depth First Search (DFS) is O(V + E), where V is the number of vertices and E is the number of edges. The space complexity is O(V) for a recursive implementation. Below are the detailed explanation of Time and Space Complexity of Depth First Search (DFS): Time Complexity of Depth First Search (DFS):Best Case of Depth First Se
2 min read
Applications, Advantages and Disadvantages of Depth First Search (DFS)
Depth First Search is a widely used algorithm for traversing a graph. Here we have discussed some applications, advantages, and disadvantages of the algorithm. Applications of Depth First Search:1. Detecting cycle in a graph: A graph has a cycle if and only if we see a back edge during DFS. So we can run DFS for the graph and check for back edges.
4 min read
Depth First Traversal ( DFS ) on a 2D array
Given a 2D array grid[][] of dimension N * M, the task is to perform the Depth - First Search traversal on the given 2D array. Examples: Input: grid[][] = {{-1, 2, 3}, {0, 9, 8}, {1, 0, 1}}Output: -1 2 3 8 1 0 9 0 1Explanation: The sequence of traversal of matrix elements using DFS is -1, 2, 3, 8, 1, 0, 9, 0, 1. Input: grid[][] = {{1, 2, 3}, {5, 6,
10 min read
Iterative Deepening Search(IDS) or Iterative Deepening Depth First Search(IDDFS)
There are two common ways to traverse a graph, BFS and DFS. Considering a Tree (or Graph) of huge height and width, both BFS and DFS are not very efficient due to following reasons. DFS first traverses nodes going through one adjacent of root, then next adjacent. The problem with this approach is, if there is a node close to root, but not in first
10 min read
Iterative Depth First Traversal of Graph
Depth First Traversal (or Search) for a graph is similar to Depth First Traversal (DFS) of a tree. The only catch here is, unlike trees, graphs may contain cycles, so a node might be visited twice. To avoid processing a node more than once, use a boolean visited array. Example: Input: n = 4, e = 6 0 -&gt; 1, 0 -&gt; 2, 1 -&gt; 2, 2 -&gt; 0, 2 -&gt;
15+ min read
Check if a graph is strongly connected | Set 1 (Kosaraju using DFS)
Given a directed graph, find out whether the graph is strongly connected or not. A directed graph is strongly connected if there is a path between any two pair of vertices. For example, following is a strongly connected graph. It is easy for undirected graph, we can just do a BFS and DFS starting from any vertex. If BFS or DFS visits all vertices,
13 min read
Check if the given permutation is a valid DFS of graph
Given a graph with N nodes numbered from 1 to N and M edges and an array of numbers from 1 to N. Check if it is possible to obtain any permutation of array by applying DFS (Depth First Traversal) on given graph. Prerequisites: DFS | Map in CPP Examples: Input: N = 3, M = 2 Edges are: 1) 1-2 2) 2-3 P = {1, 2, 3} Output: YES Explanation: Since there
12 min read
Check if a given graph is Bipartite using DFS
Given a connected graph, check if the graph is bipartite or not. A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color. Note that it is possible to color a cycle graph with an even cycle using two colors. For example, see the following graph. It is not possible t
9 min read
Tree, Back, Edge and Cross Edges in DFS of Graph
Consider a directed graph given in below, DFS of the below graph is 1 2 4 6 3 5 7 8. In below diagram if DFS is applied on this graph a tree is obtained which is connected using green edges. Tree Edge: It is an edge which is present in the tree obtained after applying DFS on the graph. All the Green edges are tree edges. Forward Edge: It is an edge
11 min read
Printing pre and post visited times in DFS of a graph
Depth First Search (DFS) marks all the vertices of a graph as visited. So for making DFS useful, some additional information can also be stored. For instance, the order in which the vertices are visited while running DFS. Pre-visit and Post-visit numbers are the extra information that can be stored while running a DFS on a graph and which turns out
8 min read
Minimum number of edges between two vertices of a graph using DFS
Given an undirected graph G(V, E) with N vertices and M edges. We need to find the minimum number of edges between a given pair of vertices (u, v). We have already discussed this problem using the BFS approach, here we will use the DFS approach. Examples: Input: For the following given graph, find the minimum number of edges between vertex pair (0,
10 min read
Calculate number of nodes between two vertices in an acyclic Graph by DFS method
Given a connected acyclic graph consisting of V vertices and E edges, a source vertex src, and a destination vertex dest, the task is to count the number of vertices between the given source and destination vertex in the graph. Examples: Input: V = 8, E = 7, src = 7, dest = 8, edges[][] ={{1 4}, {4, 5}, {4, 2}, {2, 6}, {6, 3}, {2, 7}, {3, 8}}Output
10 min read
Traverse graph in lexicographical order of nodes using DFS
Given a graph, G consisting of N nodes, a source S, and an array Edges[][2] of type {u, v} that denotes that there is an undirected edge between node u and v, the task is to traverse the graph in lexicographical order using DFS. Examples: Input: N = 10, M = 10, S = 'a', Edges[][2] = { { 'a', 'y' }, { 'a', 'z' }, { 'a', 'p' }, { 'p', 'c' }, { 'p', '
8 min read
When to use DFS or BFS to solve a Graph problem?
Generally, when we come across a graph problem, we might need to traverse the structure of the given graph or tree to find our solution to the problem. Our problem might be : To search for a particular node in the graph.To find the shortest distance from a node to any other node or to every other node.To count all the nodes.Or there can be more com
7 min read
Print the lexicographically smallest DFS of the graph starting from 1
Given a connected graph with N vertices and M edges. The task is to print the lexicographically smallest DFS traversal of the graph starting from 1. Note that the vertices are numbered from 1 to N.Examples: Input: N = 5, M = 5, edges[] = {{1, 4}, {3, 4}, {5, 4}, {3, 2}, {1, 5}} Output: 1 4 3 2 5Input: N = 5, M = 8, edges[] = {{1, 4}, {3, 4}, {5, 4}
12 min read
Graph implementation using STL for competitive programming | Set 1 (DFS of Unweighted and Undirected)
We have introduced Graph basics in Graph and its representations. In this post, a different STL-based representation is used that can be helpful to quickly implement graphs using vectors. The implementation is for the adjacency list representation of the graph. Following is an example undirected and unweighted graph with 5 vertices. Below is an adj
7 min read
DFS for a n-ary tree (acyclic graph) represented as adjacency list
A tree consisting of n nodes is given, we need to print its DFS. Examples : Input : Edges of graph 1 2 1 3 2 4 3 5 Output : 1 2 4 3 5 A simple solution is to do implement standard DFS. We can modify our approach to avoid extra space for visited nodes. Instead of using the visited array, we can keep track of parent. We traverse all adjacent nodes bu
4 min read
Transitive Closure of a Graph using DFS
Given a directed graph, find out if a vertex v is reachable from another vertex u for all vertex pairs (u, v) in the given graph. Here reachable means that there is a path from vertex u to v. The reach-ability matrix is called transitive closure of a graph. For example, consider below graph: Transitive closure of above graphs is 1 1 1 1 1 1 1 1 1 1
8 min read
Sum of minimum element at each depth of a given non cyclic graph
Given a non-cyclic graph having V nodes and E edges and a source node S, the task is to calculate the sum of the minimum element at each level from source node S in the given graph.Examples: Input: S = 0, Below is the given graph Output: 5 Explanation: There is only one node at depth 0 i.e. 0. At depth 1 there are 3 nodes 1, 2, 3, and minimum of th
11 min read
Breadth First Search or BFS for a Graph
Breadth First Search (BFS) is a fundamental graph traversal algorithm. It begins with a node, then first traverses all its adjacent. Once all adjacent are visited, then their adjacent are traversed. This is different from DFS in a way that closest vertices are visited before others. We mainly traverse vertices level by level. A lot of popular graph
15+ min read
Breadth-first Search is a special case of Uniform-cost search
In AI there are mainly two types of search techniques: Un-informed/blind search techniquesInformed search techniques Search algorithms under the Uninformed category are: Breadth-first searchUniform cost searchDepth-first searchDepth limited searchIterative deepening depth-first searchBidirectional search Search algorithms under the Informed categor
6 min read
Difference between Best-First Search and A* Search?
Best-First Search: Best-First search is a searching algorithm used to find the shortest path which uses distance as a heuristic. The distance between the starting node and the goal node is taken as heuristics. It defines the evaluation function for each node n in the graph as f(n) = h(n) where h(n) is heuristics function. A*Search: A*search is a se
2 min read
Best First Search (Informed Search)
In BFS and DFS, when we are at a node, we can consider any of the adjacent as the next node. So both BFS and DFS blindly explore paths without considering any cost function.  The idea of Best First Search is to use an evaluation function to decide which adjacent is most promising and then explore. Best First Search falls under the category of Heuri
9 min read
Subtree of all nodes in a tree using DFS
Given n nodes of a tree and their connections, print Subtree nodes of every node.Subtree of a node is defined as a tree which is a child of a node. The name emphasizes that everything which is a descendant of a tree node is a tree too, and is a subset of the larger tree. Examples : Input: N = 5 0 1 1 2 0 3 3 4 Output: Subtree of node 0 is 1 2 3 4 S
8 min read
Print the DFS traversal step-wise (Backtracking also)
Given a graph, the task is to print the DFS traversal of a graph which includes every step including the backtracking. 1st step:- 0 -&gt; 1 2nd step:- 1 -&gt; 5 3rd step:- 5 -&gt; 1 (backtracking step) 4th step:- 1 -&gt; 6... and so on till all the nodes are visited. Dfs step-wise(including backtracking) is: 0 1 5 1 6 7 8 7 6 1 0 2 4 2 9 3 10 Note:
10 min read
Queries for DFS of a subtree in a tree
Given a tree of N nodes and N-1 edges. The task is to print the DFS of the subtree of a given node for multiple queries. The DFS must include the given node as the root of the subtree. In the above tree, if 1 is given as the node, then the DFS of subtree will be 1 2 4 6 7 5 3.If 2 is given as the node, then the DFS of the subtree will be 2 4 6 7 5.
11 min read
Queries for M-th node in the DFS of subtree
Given a tree of N nodes and N-1 edges. Also given an integer M and a node, the task is to print the M-th node in the DFS of the subtree of a given node for multiple queries. Note: M will not be greater than the number of nodes in the subtree of the given node. Input: M = 3, node = 1 Output: 4 In the above example if 1 is given as the node, then the
10 min read
Article Tags :
Practice Tags :