DFS
Depth-first search walks a graph by going as deep as possible along one path before backtracking. It is implemented with recursion or an explicit stack. It finds cycles, topological order, connected components, and paths; it does not find unweighted shortest paths.
Detailed Explanation
BFS expands a ring. DFS dives. From a node you pick a neighbour, finish that whole subgraph, then try the next neighbour. The call stack (or an explicit std::stack) holds the path you have not yet finished.
Recursive form on an adjacency list:
void dfs(int u) {
seen[u] = true;
for (int v : g[u])
if (!seen[v]) dfs(v);
}
That visits every node in u's component. Pre-order work goes before the loop; post-order work goes after. Topological sort of a DAG is post-order reversed. Cycle detection in a directed graph needs three colours: unvisited, on the stack, done. Seeing an on-stack neighbour is a back edge, hence a cycle.
An explicit stack simulates the recursion and will not overflow the thread stack on a deep chain. Push the start. While not empty, pop, skip if seen, mark, push neighbours. The visit order differs slightly from the recursive version unless you push neighbours in reverse to mimic the call order.
On a grid, DFS flood-fills a region (seen[r][c] = true, recurse to four neighbours). Recursion depth equals the region size; a 1000×1000 blob can overflow. Prefer BFS or an explicit stack for large fills.
Complexity is O(V + E) with a visited array. Without visited, a cyclic graph loops forever. On a tree, skipping the parent is enough.
DFS trees classify edges: tree edges, back edges (to an ancestor), forward edges, cross edges. Bridges and articulation points use discovery times and low-link values (Tarjan / Hopcroft-Tarjan). You do not need those for everyday traversal; you do for "critical connections" interview problems.
Use DFS when the problem is about structure (cycle, component, finish order) or about exploring a search tree (backtracking is DFS with undo). Use BFS when the problem is fewest edges.
Code Examples
#include <cstddef>
#include <iostream>
#include <vector>
void dfs(const std::vector<std::vector<int>>& g, int u, std::vector<char>& seen) {
seen[static_cast<std::size_t>(u)] = 1;
for (int v : g[static_cast<std::size_t>(u)]) {
if (!seen[static_cast<std::size_t>(v)]) dfs(g, v, seen);
}
}
int components(const std::vector<std::vector<int>>& g) {
std::vector<char> seen(g.size());
int n = 0;
for (int u = 0; u < static_cast<int>(g.size()); ++u) {
if (seen[static_cast<std::size_t>(u)]) continue;
dfs(g, u, seen);
++n;
}
return n;
}
int main() {
std::vector<std::vector<int>> g{{1}, {0}, {}};
std::cout << components(g) << '\n'; // prints: 2
}#include <stack>
#include <vector>
void dfsIter(const std::vector<std::vector<int>>& g, int start, std::vector<char>& seen) {
std::stack<int> st;
st.push(start);
while (!st.empty()) {
int u = st.top();
st.pop();
if (seen[static_cast<std::size_t>(u)]) continue;
seen[static_cast<std::size_t>(u)] = 1;
for (int v : g[static_cast<std::size_t>(u)]) st.push(v);
}
}Common Gotchas
Recursion on a long path overflows the C++ stack
a list of 100,000 nodes as a "tree" will crash. Iterate.
Directed cycle detection needs three states
a boolean `seen` is not enough; a neighbour can be done (safe) or grey (cycle).
First-time reach in DFS is not a shortest path
the first time you see a node can be a long detour. Use BFS for hop count.
Mutating the graph during DFS
adding edges as you go invalidates adjacency iterators on some representations. Snapshot or use indices.