Depth-First Search (DFS) is an algorithm for traversing or searching through tree or graph data structures. It explores as far down a branch as possible before backtracking. This method can be implemented using recursion or a stack.
Initialize:
Process the Stack:
Repeat until all nodes are visited.
Here’s an implementation of DFS using an adjacency list representation of a graph in C++:
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class Graph {
private:
int V; // Number of vertices
vector<vector<int>> adj; // Adjacency list
public:
Graph(int v) : V(v), adj(v) {}
void addEdge(int u, int v) {
adj[u].push_back(v); // Add edge from u to v
// If undirected, uncomment the next line:
// adj[v].push_back(u); // Add edge from v to u
}
void DFS(int start) {
vector<bool> visited(V, false); // Track visited vertices
stack<int> s; // Stack for DFS
s.push(start); // Push the start node onto the stack
while (!s.empty()) {
int node = s.top(); // Get the top node
s.pop(); // Remove the top node
if (!visited[node]) {
visited[node] = true; // Mark the node as visited
cout << node << " "; // Process the node
// Push all adjacent unvisited nodes onto the stack
for (int i = adj[node].size() - 1; i >= 0; --i) {
if (!visited[adj[node][i]]) {
s.push(adj[node][i]);
}
}
}
}
cout << endl; // New line after traversal
}
};
int main() {
Graph g(5); // Create a graph with 5 vertices
g.addEdge(0, 1);
g.addEdge(0, 4);
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(2, 3);
g.addEdge(3, 4);
cout << "DFS Traversal starting from vertex 0: ";
g.DFS(0); // Start DFS from vertex 0
return 0;
}
Graph Class:
DFS Function:
Main Function:
Time Complexity:
Space Complexity:
Depth-First Search is a versatile traversal algorithm that systematically explores branches of a graph. Its use of a stack allows for deep exploration, making it suitable for a variety of applications in graph theory, pathfinding, and solving problems that involve backtracking. Understanding DFS is essential for solving complex problems in computational fields.
Open this section to load past papers