Hook!!!
Hello everyone!
If you are struggling with graph problems, this post will save you a LOT of time. Today I will explain one of the most powerful techniques — DFS (Depth-First Search)
What is DFS? DFS is a technique where we go as deep as possible in a graph before backtracking.
In simple words: Go forward → go deeper → if stuck → go back
Where is it used? DFS is used in:
1) Connected components 2) Cycle detection 3) Tree traversal 4) Grid problems (VERY COMMON)
Pattern If you see:
- "graph"
- "visit all nodes"
- "connected"
- "grid"
Think about DFS immediately
Code (C++) **#include <bits/stdc++.h> using namespace std;
const int N = 200005;
vector g[N]; bool vis[N];
void dfs(int v) { vis[v] = true;
for (int to : g[v]) {
if (!vis[to]) {
dfs(to);
}
}}
int main() { int n, m; cin >> n >> m;
for (int i = 0; i < m; i++) {
int u, v;
cin >> u >> v;
g[u].push_back(v);
g[v].push_back(u);
}
int cnt = 0;
for (int i = 1; i <= n; i++) {
if (!vis[i]) {
dfs(i);
cnt++;
}
}
cout << cnt << "\n";}**
Final Tip DFS is one of the easiest ways to gain rating on Codeforces.
Master it → solve 50+ problems → you will feel huge progress
Ending Thanks for reading!
If this post helped you: please upvote Good Bye!







