Introduction
Breadth-first search explores in rings. Depth-first search (DFS) does the opposite: it follows one path as far as it can, then backs up and tries the next. DFS is the shortest code of all graph algorithms, a few lines of recursion, and it answers questions BFS cannot: which vertices are connected, how big is each group, and does the graph have a cycle.
How it works
The recursion
void dfs(int u) {
seen[u] = true;
for (int v : adj[u])
if (!seen[v]) dfs(v);
}
Mark the vertex as seen, then visit each unseen neighbour. Marking first is what stops the search from going round in circles. Each vertex is visited once and each edge looked at once, so the cost is O(n + m).
Connected components
A connected component is a group of vertices that can all reach each other. To count them, loop over all vertices; whenever one is not yet seen, you have found a new component, so add one and run DFS from it, which marks the whole group. Counting a component's size is just a counter that goes up each time DFS enters a vertex.
Grids
The same idea works on grids. Treat each # cell as a vertex and its four neighbours as edges. One DFS from an unseen # cell marks a whole island. Keep the direction arrays dr and dc from the BFS lesson and check the bounds first.
Cycles in a directed graph
Use three colours: 0 not visited, 1 on the current path, 2 finished. If DFS meets a neighbour with colour 1, it has come back to a vertex on its own path: a cycle. A graph of tasks with "A before B" edges can be ordered only if it has no cycle.
Recursion depth. DFS uses the call stack, one frame per step of the path. On a path of 10⁶ vertices the stack can overflow on a judge. For huge inputs, use BFS or an explicit stack.
Example
#include <iostream>
#include <vector>
using namespace std;
vector<vector<int>> adj(8);
vector<bool> seen(8, false);
void dfs(int u) {
seen[u] = true;
for (int v : adj[u])
if (!seen[v]) dfs(v);
}
int main() {
int edges[5][2] = {{0, 1}, {1, 2}, {3, 4}, {5, 6}, {6, 5}};
for (int i = 0; i < 5; i++) {
adj[edges[i][0]].push_back(edges[i][1]);
adj[edges[i][1]].push_back(edges[i][0]);
}
int components = 0;
for (int u = 0; u < 8; u++) {
if (!seen[u]) {
components++;
dfs(u);
}
}
cout << "components: " << components << "\n";
return 0;
}The graph has 8 vertices (0 to 7) and the edges 0-1, 1-2, 3-4 and 5-6 (the last is given twice). The program counts its connected components.
Line by line
adjandseenare global so thatdfscan use them without extra arguments.dfs(u)marksuand recurses into every neighbour not yet seen.- The loop over
ustarts a new DFS only at vertices not seen yet; each start is one new component. - The edge 5-6 is added twice, which is harmless: the neighbour is simply already seen.
- Vertex 7 has no edges, so it is a component of its own.
Expected result
components: 4
In the real world
Components find groups of friends in a network, separate islands on a map, and check whether a network is still connected after a failure. Paint-bucket tools in image editors flood a region with DFS or BFS. Build systems and spreadsheets use cycle detection to find circular dependencies, and topological order to decide what to build first.
Common mistakes
- Marking a vertex seen after the recursive calls instead of before them, which can loop forever.
- Forgetting to reset
seenwhen there are several test cases. - Recursing on a very long path and overflowing the stack.
- Counting components inside
dfsinstead of in the outer loop. - Treating a directed graph as undirected when looking for cycles.
Best practices
- Mark vertices seen as the first line of
dfs. - Keep
adjandseenglobal or pass them by reference, never by value. - Count components in the outer loop over vertices.
- Use three colours for directed cycles.
- Think about the recursion depth before you pick DFS.
Summary
DFS follows a path to its end, marking vertices on the way, and costs O(n + m). Run it once from every unseen vertex to count components, count entries to measure them, and use a third state to find directed cycles. The same code floods grid islands.
Quick check
Key takeaways
- DFS visits each vertex once by marking it seen before going deeper
- One DFS per unseen vertex counts the components
- The same code floods a grid by using four neighbours
- A directed cycle shows up as an edge back to a vertex still on the current path
Practice problems for this lesson
Was this lesson clear?
My notes
Write down what you want to remember from this lesson. Notes are saved on this device as you type, and appear on your dashboard.