Table of contents | |
Introduction | |
Overview of DFS | |
DFS Implementation in C++ | |
Examples and Code Explanation | |
Sample Problems and Solutions |
To implement DFS, we need to represent the graph using an adjacency list or matrix. Here, we will use an adjacency list representation. We will also maintain a visited array to keep track of visited vertices.
C++ Code (Recursive DFS):
#include <iostream>
#include <vector>
using namespace std;
// Function to perform DFS recursively
void dfsUtil(vector<vector<int>>& graph, int v, vector<bool>& visited) {
visited[v] = true;
cout << v << " ";
for (int u : graph[v]) {
if (!visited[u]) {
dfsUtil(graph, u, visited);
}
}
}
// Function to initialize DFS and handle disconnected components
void dfs(vector<vector<int>>& graph, int V) {
vector<bool> visited(V, false);
for (int v = 0; v < V; ++v) {
if (!visited[v]) {
dfsUtil(graph, v, visited);
}
}
}
// Driver code
int main() {
int V = 5; // Number of vertices
vector<vector<int>> graph(V);
// Adding edges to the graph
graph[0].push_back(1);
graph[0].push_back(2);
graph[1].push_back(2);
graph[2].push_back(0);
graph[2].push_back(3);
graph[3].push_back(3);
cout << "DFS traversal: ";
dfs(graph, V);
return 0;
}
Output:
DFS traversal: 0 1 2 3
Let's go through two examples to understand how DFS works.
Example 1: Simple Connected Graph
Consider the following graph:
0
/ \
1 2
/ \
3 3
The code provided in the previous section will produce the DFS traversal output: 0 1 2 3.
Explanation:
Example 2: Disconnected Graph
Consider the following graph:
0 3
/ \
1 2
4 5
The code provided in the previous section will produce the DFS traversal output: 0 1 2 3 4 5.
Explanation:
Problem 1: Given an undirected graph, find the number of connected components.
- Initialize a counter variable to 0.
- Use the DFS algorithm to traverse the graph, incrementing the counter for each disconnected component encountered.
- The final counter value will represent the number of connected components.
Problem 2: Given a directed graph, check if it contains a cycle.
- Use the DFS algorithm to traverse the graph.
- Maintain a visited array and a recursion stack to detect cycles.
- If, during the DFS traversal, we encounter a vertex that is already visited and is present in the recursion stack, a cycle is detected.
Depth-First Search (DFS) is a powerful graph traversal algorithm used to explore graphs systematically. In this article, we provided a beginner's guide to DFS, explaining its basic concepts and providing a C++ implementation. We covered examples and code explanations to help you understand the algorithm better. Additionally, we presented sample problems and solutions to demonstrate the practical applications of DFS. By mastering DFS, you will be equipped to solve a wide range of graph-related problems efficiently.
153 videos|115 docs|24 tests
|
|
Explore Courses for Software Development exam
|