DEV Community is a community of 789,160 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Nic

Posted on • Originally published at coderscat.com on

Depth-First-Search(DFS) Explained With Visualization

DFS Overview

The Depth First Search(DFS) is the most fundamental search algorithm used to explore the nodes and edges of a graph. It runs with time complexity of O(V+E), where V is the number of nodes, and E is the number of edges in a graph.

DFS is often used as a building block in other algorithms; it can be used to:

1. A naive solution for any searching problem.
2. Finding connected components or strongly connected components.
3. Topological sorting.
4. Finding the bridges of a graph.
5. Detect cycles in a graph.

DFS Visualization on Maze

The source is at the position of left-up, and the target is the position of right-bottom.

As we can see, DFS explores as far as possible along each branch before backtracking: The maze is generated by disjoint set.

The recursive implementation

#include <list>
#include <vector>
#include <iostream>
using namespace std;

class Graph {
int V;
bool DFS_rec(int v, int t, vector<bool>& visited);

public:
Graph(int V);
bool DFS(int v, int t);
};

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

void Graph::addEdge(int v, int w) {
}

bool Graph::DFS_rec(int v, int t, vector<bool>& visited) {
visited[v] = true;
cout << v << " ";
if(v == t) return true; // Find a path

if (!visited[*it] && DFS_rec(*it, t, visited))
return true;
}
return false;
}

bool Graph::DFS(int v, int t) {
vector<bool> visited(V, false);
return DFS_rec(v, t, visited);
}

int main() {
Graph g(4);

cout << "Following is Depth First Traversal (0 -> 3): \n";
if(g.DFS(0, 3)) cout << "\nFind a Path!" << std::endl;
else cout << "\nNo Path!" << std::endl;
return 0;
}

The iterative implementation

A non-recursive implementation of DFS needs the data-structure of stack.

The worst-case space complexity is O(E).

bool Graph::DFS(int v, int t) {
vector<bool> marked(V, false);

stack<int> S;
S.push(v);
marked[v] = true;
while(!S.empty()) {
int n = S.top(); S.pop();
cout << n << " ";
if(n == t) //Find a path to target
return true;
if(!marked[*it]) {
marked[*it] = true;
S.push(*it);
}
}
}
return false;
}

References

The post Depth-First-Search(DFS) Explained With Visualization appeared first on CodersCat.

Discussion (1) Great Article!!

I'm doing a large work to create a comprehensive header-only library for C++ for graph Representation, Manipulation, Partitioning and Algorithms.

I'm looking for Contributor, but also a simple feedback is good enough.
If you have 5 min to check my repo I'd be very grateful. ZigRazor / CXXGraph

Header-Only C++ Library for Graph Representation and Algorithms

Thank you so much in advance.
Best regards