DFS
Depth-First Search | Поиск в глубину — is a graph traversal algorithm that explores each branch as deep as possible before backtracking. Starting from the start vertex, the algorithm goes to the first unvisited neighbor, then to its first unvisited neighbor, and so on until it reaches a dead end. After that, it backtracks to the previous vertex, and the process repeats for the remaining neighbors.
Imagine walking through a maze, always choosing the left turn, and going until you hit a wall. Then you return to the last intersection and try another path — that’s how DFS explores a graph.
Typical DFS implementation code (recursive)
// DFS implementation (recursive)
#include <iostream>
#include <vector>
using namespace std;
void dfs(int v, vector<vector<int>>& graph, vector<bool>& visited)
{
visited[v] = true;
cout << v << " ";
for (int neighbor : graph[v])
{
if (!visited[neighbor])
{
dfs(neighbor, graph, visited);
}
}
}
int main() {
// Graph: 0-1, 0-2, 1-3, 2-3
vector<vector<int>> graph =
{
{1, 2},
{0, 3},
{0, 3},
{1, 2}
};
vector<bool> visited(graph.size(), false);
dfs(0, graph, visited); // Output: 0 1 3 2
return 0;
}
Details
Key properties
- Uses a stack (
LIFO): last in — first out. In the recursive implementation, the call stack is used implicitly. - Does not guarantee the shortest path in unweighted graphs (unlike BFS).
- Complexity:
O(V + E)(V— vertices,E— edges).
How it works (step by step)
- Mark the current vertex
vas visited and process it. - For each neighbor
uof vertexv:- If
uis not visited, recursively calldfs(u).
- If
- If vertex
vhas no unvisited neighbors left, backtrack to the calling vertex.
Where it’s used
- Connectivity check: determining whether a path exists between two vertices.
- Cycle detection: finding cycles in a graph (using vertex colors: white, gray, black).
- Topological sorting: ordering vertices of a directed acyclic graph.
- Finding strongly connected components: Kosaraju’s algorithm.
- Maze generation and puzzle solving: backtracking.
Difference from BFS (breadth-first search)
- DFS uses a
stack(or recursion), goesdeep, and does not guarantee the shortest path. - BFS uses a
queue, searcheswide, andguaranteesthe shortest path in an unweighted graph.
Example LeetCode problems
Let’s go through 3 typical LeetCode problems — from easy to medium. For each one, I’ve provided the key idea, the code, and a brief explanation.
1. LeetCode 200 — Number of Islands (Medium)
🔗 leetcode link
Problem:
Given a 2D grid grid of '1' (land) and '0' (water). An island is a group of land cells connected 4-directionally. Return the number of islands.
Solution:
Scan the grid. As soon as we find a '1', increment the counter and run DFS to “sink” the entire island (mark all connected cells as visited).
Solution code
class Solution {
public:
void dfs(vector<vector<char>>& grid, int r, int c)
{
int rows = grid.size();
int cols = grid[0].size();
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == '0') {
return;
}
grid[r][c] = '0'; // "Sink" the cell
dfs(grid, r + 1, c);
dfs(grid, r - 1, c);
dfs(grid, r, c + 1);
dfs(grid, r, c - 1);
}
int numIslands(vector<vector<char>>& grid)
{
if (grid.empty() || grid[0].empty()) return 0;
int rows = grid.size();
int cols = grid[0].size();
int islands = 0;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (grid[r][c] == '1')
{
islands++;
dfs(grid, r, c);
}
}
}
return islands;
}
};
Complexity: O(N×M) — each cell is visited at most once.
2. LeetCode 695 — Max Area of Island (Medium)
Problem:
Given a binary matrix grid. An island is a group of connected 1s. The area of an island is the number of cells with 1. Return the maximum area of an island. If there are no islands — return 0.
Solution:
Similar to the previous problem, but instead of counting the number of islands, DFS returns the area of each island. We track the maximum.
Solution code
class Solution {
public:
int dfs(vector<vector<int>>& grid, int r, int c)
{
int rows = grid.size();
int cols = grid[0].size();
if (r < 0 || r >= rows || c < 0 || c >= cols || grid[r][c] == 0) {
return 0;
}
grid[r][c] = 0; // Mark as visited
int area = 1;
area += dfs(grid, r + 1, c);
area += dfs(grid, r - 1, c);
area += dfs(grid, r, c + 1);
area += dfs(grid, r, c - 1);
return area;
}
int maxAreaOfIsland(vector<vector<int>>& grid)
{
if (grid.empty() || grid[0].empty()) return 0;
int rows = grid.size();
int cols = grid[0].size();
int maxArea = 0;
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < cols; c++)
{
if (grid[r][c] == 1)
{
maxArea = max(maxArea, dfs(grid, r, c));
}
}
}
return maxArea;
}
};
Complexity: O(N×M) — each cell is visited once.
Key trick: DFS returns the accumulated area, which lets us elegantly sum up the size of a component.
3. LeetCode 133 — Clone Graph (Medium)
Problem:
Given a node node of a connected undirected graph. Return a deep copy (clone) of the graph. Each node contains a value val and a list of neighbors neighbors.
Solution:
DFS using a hash table (unordered_map) that stores the mapping between an original node and its clone. When visiting a node, if it’s not yet in the table, create a clone and recursively clone all neighbors.
Solution code
class Solution {
public:
unordered_map<Node*, Node*> cloned;
Node* dfs(Node* node)
{
if (!node) return nullptr;
// If the node is already cloned, return its copy
if (cloned.count(node)) {
return cloned[node];
}
// Create a new clone node
Node* copy = new Node(node->val);
cloned[node] = copy;
// Recursively clone the neighbors
for (Node* neighbor : node->neighbors) {
copy->neighbors.push_back(dfs(neighbor));
}
return copy;
}
Node* cloneGraph(Node* node)
{
return dfs(node);
}
};
Complexity: O(V + E), where V — number of vertices, E — number of edges. Each node and each edge is processed once.
Useful techniques for using DFS on LeetCode problems
- Visited — for graphs use
unordered_setorvector<bool>; for grids, modify the matrix itself (replace with'0'or0) or use a separatevector<vector<bool>>. - Don’t forget backtracking — in enumeration problems (e.g., Word Search), after the recursive call you must restore the cell’s original state.
- Call stack — recursive DFS can cause stack overflow on large graphs (e.g., a 1000×1000 grid). In such cases, use iterative DFS with an explicit
stack. - Vertex colors — for cycle detection use three colors: white (unvisited), gray (in progress), black (processed). If during traversal from a gray vertex we reach another gray vertex — a cycle is found.
- DFS on grids — don’t forget the boundaries (
r < 0 || r >= rows || c < 0 || c >= cols) and the visit condition check (grid[r][c] == '0'orvisited[r][c]).
📖 Read this lesson in Russian