π Quick BFS Recap
In Breadth-First Search (BFS), you explore the graph level by level.
π§ Think of it like:
Youβre standing in a room and shout, βWhoβs next to me?β
You visit all immediate neighbors first, then move on to their neighbors, and so on.
π¦ Uses a queue (FIFO)
β
Best for shortest path in unweighted graphs
π Real-life: friend suggestions, web crawling, peer-to-peer networks
Now, Letβs Dive into DFS β Depth-First Search
No more level-by-level. Itβs time to go DEEP!
In DFS, you pick a path and go as deep as possible, only backtracking when thereβs nowhere left to go.
π§ Imagine: You enter a maze and just keep walking forward till you hit a dead-end, then backtrack and explore the next path.
π¦Uses recursion or a stack
β
Best for:
Exploring complete paths
Detecting cycles
Maze solving
Topological sort
π What is DFS?
Depth-First Search (DFS) is a classic graph traversal algorithm.
Instead of exploring layer by layer like BFS, it dives deep into each branch of a graph or tree before backtracking.
π§ How It Works:
Start from a node (e.g., node 0).
Use a stack (or recursion) to track your path.
Keep a visited[] array to avoid revisiting nodes.
For each node:
Visit it.
Dive into its first unvisited neighbor.
Repeat until stuck, then backtrack.
π₯ Stack behavior: Last in, first out (LIFO) β perfect for going deep before backtracking!
π§ Graph Structure (Adjacency List based on the image):
From the graph:
1: [2, 3]
2: [1, 4]
3: [1, 5]
4: [2, 5]
5: [3, 4]
Weβll assume:
Itβs an undirected graph.
DFS starts from node 1.
β
Dry Run of DFS
Step-by-Step (Recursive DFS)
Start at 1, mark visited β dfs = [1]
Go to neighbor 2 (first unvisited of 1) β dfs = [1, 2]
Go to neighbor 4 (from 2) β dfs = [1, 2, 4]
Go to neighbor 5 (from 4) β dfs = [1, 2, 4, 5]
Go to neighbor 3 (from 5) β dfs = [1, 2, 4, 5, 3]
All neighbors visited. Backtrack until all paths are done.
π Final DFS Traversal Order:
1 β 2 β 4 β 5 β 3
β
DFS Code in C++
#include <iostream>
#include <vector>
using namespace std;
// Helper method to perform DFS recursively
void dfsHelper(int node, vector<int> adj[], vector<bool>& visited, vector<int>& dfs) {
visited[node] = true;
dfs.push_back(node);
for (int neighbor : adj[node]) {
if (!visited[neighbor]) {
dfsHelper(neighbor, adj, visited, dfs);
}
}
}
// DFS function that calls the helper
vector<int> dfsOfGraph(int V, vector<int> adj[]) {
vector<int> dfs;
vector<bool> visited(V, false);
dfsHelper(0, adj, visited, dfs); // starting from node 0
return dfs;
}
int main() {
int V = 5;
vector<int> adj[V];
// 1-2, 1-3, 2-4, 3-5, 4-5
adj[0] = {1, 2}; // node 1 -> 2, 3
adj[1] = {0, 3}; // node 2 -> 1, 4
adj[2] = {0, 4}; // node 3 -> 1, 5
adj[3] = {1, 4}; // node 4 -> 2, 5
adj[4] = {2, 3}; // node 5 -> 3, 4
vector<int> result = dfsOfGraph(V, adj);
cout << "DFS Traversal: ";
for (int node : result)
cout << node + 1 << " ";
cout << endl;
return 0;
}
Top comments (0)