Learn the pattern · ~15 min
Graph BFS / DFS
also called flood fill, connected components, unweighted shortest path
Visit every reachable cell exactly once and mark it as you go. Each fresh start of the walk is one new component.
Reach for it when you read
- +"Fewest moves / steps / minutes" where every move costs the same: BFS.
- +Count or measure groups of connected cells or nodes: islands, provinces, regions.
- +Several starting points spread at once (rotting, fire, distance to the nearest gate): multi-source BFS.
- +The nodes are states (a word, a lock code, a board) and the edges are legal moves.
- +Mark what's reachable from somewhere, like the border, and treat the rest differently.
Not this one when
- ×Steps cost different amounts: Dijkstra (or 0-1 BFS when the costs are only 0 and 1).
- ×Merging groups while edges keep arriving, with "same group?" queries in between: union-find.
- ×An order where some tasks must come before others: topological sort.
Learn Graph BFS / DFS
First, what is a graph, and what does "traverse" mean?
A graph is nodes joined by edges. Seven nodes, 0 to 6:
No arrows, so it's undirected: you can walk 0-1 both ways. In code it's an adjacency list, the neighbours of each node: adj[2] = {0, 3, 5}.
To traverse a graph is to visit each node reachable from a start, once. BFS (breadth-first search) spreads in rings: everything 1 edge away, then 2 edges away, and so on. DFS (depth-first search) runs down one path as far as it can, then backs up. BFS first: its rings give you distances for free.
How does BFS spread in rings?
BFS keeps a queue: first in, first out. Push node 0 with dist[0] = 0. The rule:
Take the node at the front of the queue. Every neighbour that hasn't been seen yet gets distance + 1, remembers who found it, and goes to the back of the queue.
dist and parent start at -1 (not seen yet).
| pop | what happens | queue after |
|---|---|---|
| 0 | 1 and 2 are new: dist 1, parent 0 | 1, 2 |
| 1 | 0 is seen. 3 is new: dist[3] = 2, parent[3] = 1 | 2, 3 |
| 2 | 0 and 3 are already seen, skip them. 5 is new: dist 2, parent 2 | 3, 5 |
| 3 | 1 and 2 are seen. 4 is new: dist 3, parent 3 | 5, 4 |
| 5 | its only neighbour, 2, is seen | 4 |
| 4 | 3 is seen. 6 is new: dist 4, parent 4 | 6 |
| 6 | 4 is seen; queue empty | empty |
| node | 0 | 1 | 2 | 3 | 4 | 5 | 6 |
|---|---|---|---|---|---|---|---|
| dist | 0 | 1 | 1 | 2 | 3 | 2 | 4 |
| parent | -1 | 0 | 0 | 1 | 3 | 2 | 4 |
Read the queue column: distances never go down. Every 1 leaves before the first 2. So the first time BFS reaches a node, it's by the fewest edges.
The code for it
vector<int> dist(n, -1), parent(n, -1);
queue<int> q;
dist[src] = 0;
q.push(src);
while (!q.empty()) {
int u = q.front(); q.pop();
for (int v : adj[u])
if (dist[v] == -1) { // not seen yet
dist[v] = dist[u] + 1; // mark it now, when you push
parent[v] = u;
q.push(v);
}
}You don't need to memorise this. It's the table: pop the front, give each new neighbour a distance and a parent, push it. parent rebuilds the route: from 6, follow 4, 3, 1, 0, then reverse: 0 → 1 → 3 → 4 → 6, 4 edges, matching dist[6].
Why mark a node when you push it, not when you pop it? Look at node 3. Node 1 pushed it, then node 2 touched it too. 3 was already marked, so 2 skipped it. Mark on pop and 2 pushes 3 a second time; on a grid, a cell could be queued by all 4 neighbours.
Fine, but how does this help us?
The classic problem: Rotting Oranges. A grid has 0 (empty), 1 (fresh) and 2 (rotten). Every minute, each rotten orange rots its fresh neighbours (up, down, left, right). How many minutes until none is fresh? If some orange can never rot, return -1.
c0 c1 c2 c3
r0 2 1 1 0
r1 1 1 0 1
r2 0 1 1 2By hand: two rotten, (0,0) and (2,3), and 7 fresh.
| minute | what rots | how you found it | fresh left |
|---|---|---|---|
| 1 | (1,0), (0,1), (1,3), (2,2) | the fresh neighbours of (0,0) and (2,3) | 3 |
| 2 | (1,1), (0,2), (2,1) | the fresh neighbours of the four from minute 1 | 0 |
So the answer is 2.
The brute force
Simulate it: every minute, scan the grid, collect each fresh orange touching a rotten one, rot them together.
int orangesRottingSlow(vector<vector<int>> g) {
int m = g.size(), n = g[0].size();
auto rotten = [&](int r, int c) { return r >= 0 && c >= 0 && r < m && c < n && g[r][c] == 2; };
for (int minutes = 0; ; minutes++) {
vector<pair<int, int>> rotNow; // fresh ones touching a rotten one
int fresh = 0;
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++) {
if (g[r][c] != 1) continue;
fresh++;
if (rotten(r + 1, c) || rotten(r - 1, c) || rotten(r, c + 1) || rotten(r, c - 1))
rotNow.push_back({r, c});
}
if (fresh == 0) return minutes;
if (rotNow.empty()) return -1; // fresh ones that nothing can reach
for (auto [r, c] : rotNow) g[r][c] = 2;
}
}It's correct, but each minute scans all m·n cells, and there can be about m·n minutes. LeetCode's grid is at most 10 × 10, so it passes there. Make it one row of 10⁵ cells, rotten at one end: one rots per minute, so 10⁵ minutes × 10⁵ cells = 10¹⁰ checks. At -O2 that takes about 5 seconds. Time limit exceeded.
The one thought that fixes it
Stop at minute 2. The scan checks (0,0) again, but (0,0) rotted its neighbours in minute 1: it can't find anything new. The ones that did rot something in minute 2, (1,0), (0,1) and (2,2), all rotted in minute 1. An orange that rotted earlier has done all it can: only last minute's oranges can rot anyone new.
So keep a list of last minute's oranges and look only at their neighbours. That list is a BFS queue. An orange rots at the minute equal to its distance from the nearest starting rotten orange, so put every rotten orange in the queue at minute 0: multi-source BFS.
The new line is size = q.size(): it handles one minute's oranges, then counts the minute.
int orangesRotting(vector<vector<int>>& g) {
int m = g.size(), n = g[0].size(), fresh = 0, minutes = 0;
queue<pair<int, int>> q;
for (int r = 0; r < m; r++)
for (int c = 0; c < n; c++) {
if (g[r][c] == 2) q.push({r, c}); // every source at minute 0
if (g[r][c] == 1) fresh++;
}
int dr[4] = {1, -1, 0, 0}, dc[4] = {0, 0, 1, -1};
while (!q.empty() && fresh > 0) {
for (int size = q.size(); size > 0; size--) { // this minute's oranges
auto [r, c] = q.front(); q.pop();
for (int k = 0; k < 4; k++) {
int nr = r + dr[k], nc = c + dc[k];
if (nr < 0 || nc < 0 || nr >= m || nc >= n || g[nr][nc] != 1) continue;
g[nr][nc] = 2, fresh--; // rot it now, not when popped
q.push({nr, nc});
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}Dry run
Each minute's queue holds exactly the oranges that rotted the minute before.
| minute | queue at the start | what happens | fresh left |
|---|---|---|---|
| 1 | (0,0), (2,3) | (0,0) rots (1,0), (0,1); (2,3) rots (1,3), (2,2) | 3 |
| 2 | (1,0), (0,1), (1,3), (2,2) | (1,0) → (1,1), (0,1) → (0,2), (2,2) → (2,1); (1,3) finds nothing | 0 |
| stop | (1,1), (0,2), (2,1) | fresh is 0, so the loop ends |
0 |
minutes = 2, the same answer as the brute force. Without fresh > 0 the loop runs once more, rots nothing and returns 3. On [[2,1,0],[0,0,1]] the lone 1 is cut off: the queue empties with fresh = 1, so -1.
Why it's O(m · n)
Count what happens to each cell: it enters the queue at most once (rotten stays rotten), and when it leaves it checks 4 neighbours: O(m · n) time and space. On an adjacency list, each node is pushed once and each edge looked at from both ends: O(V + E).
From O((m·n)²) down to O(m·n), by only looking at the oranges that just changed.
Counting groups? Start a new search from every unseen cell
Number of Islands: how many groups of connected 1s? Distance doesn't matter, so recursive DFS is shorter. Each time the scan meets land, count an island and sink all of it.
function<void(int, int)> sink = [&](int r, int c) {
if (r < 0 || c < 0 || r >= m || c >= n || g[r][c] != '1') return;
g[r][c] = '0'; // mark before going deeper
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};The scan does if (g[r][c] == '1') count++, sink(r, c); on every cell. On 110 / 010 / 001 it counts (0,0) and sinks (0,0), (0,1), (1,1); the next land is (2,2). Answer 2, and each cell sinks once: O(m · n).
Remember this
- Fewest steps, every step costing the same → BFS. DFS finds a path, not the shortest. Costs 0 or 1 → a deque (0-edges to the front); other costs → Dijkstra.
- Mark a node when you push it, never when you pop it, or it gets queued many times.
- Several sources spreading at once → push them all first;
size = q.size()to count levels. - Whenever a problem asks "how many groups", "can I reach it" or "fewest moves", it's a traversal.
Practise it on Flood Fill, then Number of Islands (count the starts), Max Area of Island (size of each group), Rotting Oranges (many sources), Shortest Path in Binary Matrix (fewest steps) and Word Ladder (the nodes are words).
Below, watch Number of Islands run line by line.
Watch it work, line by line
Number of Islands ↗, 110 / 010 / 001 → 2. Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.
When to use it, and when not
Ask yourself
Can I describe it as things connected to their neighbours, where I need to reach, group or count them, and every move costs the same?
Reach for it when
- +grid of cells / islands
- +connectivity or reachability
- +shortest path with equal edge weights
- +implicit graph (word ladder, states)
- +V + E up to ~1e6
It fails when
- ×Edges have differing non-negative weightsuse Dijkstra; Bellman-Ford if weights can be negative
- ×Weights are only 0 and 1use Deque BFS
- ×Dependency order on a DAGuse Topological sort
- ×Repeated merging / online connectivity queries (no paths needed)use Union-Find
- ×Edges get deleted onlineuse Reverse the deletions offline, then Union-Find
- ×You must use every edge once, not visit every vertexuse Euler path
- ×You think DFS gives the shortest pathuse BFS: DFS finds a path, not the fewest edges
Looks like it, isn't (and the other way round)
- Word Ladder looks like Backtracking, needs this pattern
Shortest transformation sequence is BFS on an implicit graph.
- Reconstruct Itinerary looks like Graph BFS / DFS, needs Eulerian Path / Circuit (Hierholzer)
Every ticket (edge) must be used exactly once: Hierholzer, not plain DFS with backtracking.
- Path With Minimum Effort looks like Graph BFS / DFS, needs Dijkstra (Weighted Shortest Path)
Cost is the max edge on the path: minimax Dijkstra (or binary search + BFS, or union-find).
- Swim in Rising Water looks like Graph BFS / DFS, needs Dijkstra (Weighted Shortest Path)
Minimax over cell heights; plain BFS ignores the cost.
- Evaluate Division looks like Graph BFS / DFS, needs Union-Find (Disjoint Set)
DFS per query works; weighted union-find answers each query in near O(1).
- Minimum Time to Visit a Cell In a Grid looks like Graph BFS / DFS, needs Dijkstra (Weighted Shortest Path)
Arrival times vary per cell and waiting changes time by 2 (back-and-forth), so it is Dijkstra with a parity correction, not BFS.
- Longest Cycle in a Graph looks like Graph BFS / DFS, needs Functional / Successor Graphs
Each node has at most one outgoing edge, so the graph is functional: walk each component once with visit timestamps.
- Number of Good Paths looks like Graph BFS / DFS, needs Union-Find (Disjoint Set)
Process vertices by increasing value, union with neighbours of lower or equal value, and count equal-valued vertices per root (Kruskal-style).
- Minimum Number of Days to Disconnect Island looks like Graph BFS / DFS, needs Bridges & Articulation Points (low-link)
The answer is always <= 2: 0 if already disconnected, 1 if an articulation cell exists (editorial: Tarjan), else 2.
Why this pattern and not another
You must explore reachable nodes of a graph/grid — counting regions, filling, or shortest unweighted distance — visiting each node once with a visited set to handle cycles.
Recall card
Answer each one out loud before you open it. Come back in three days and try again without reading the page.
1Why must a cell be marked visited before you explore its neighbours?Reveal
Otherwise a neighbour walks straight back into it, and DFS loops forever (or BFS queues it many times).
2DFS or BFS for the fewest steps in a maze where every move costs 1?Reveal
BFS. It reaches cells in rings of 1, 2, 3 steps, so the first visit is the shortest. DFS order says nothing about distance.
3What's the cost of flood-filling an R × C grid, and why?Reveal
O(R · C). Each cell is marked once and then never entered again, and each has at most 4 neighbours to check.
Practice ladder
- 1Flood Fillone floodEasy
- 2Number of Islandsthe hookMedium
- 3Max Area of Islandsize of each componentMedium
- 4Rotting Orangesmany starting pointsMedium
- 5Surrounded Regionsflood from the borderMedium
- 6Shortest Path in Binary Matrixfewest stepsMedium
- 7Is Graph Bipartite?two-colouringMedium
- 8Word Ladderthe graph is hiddenHard
Finished Graph BFS / DFS? Mark it done and Lessgo moves you to the next step.