Graph Patterns (Grids, Islands, BFS & DFS)
Flood fill, counting islands, multi-source BFS, shortest paths in grids, and cloning — the graph problems interviews love.
Most interview graph problems don't hand you an adjacency list. They give a grid, a set of words, or a state — and you must see the implicit graph. Once you do, it's BFS or DFS with a visited set.
- A 2D grid of cells (land/water, open/wall, colours) with up/down/left/right moves.
- "Number of connected regions", "size of the largest region", "fill a region".
- "Minimum steps / time to reach…" → BFS.
- Transformations of a state one step at a time (word ladder, lock combinations, sliding puzzles).
Template: grid DFS (flood fill / islands)
int numIslands(char[][] g) {
int count = 0;
for (int r = 0; r < g.length; r++)
for (int c = 0; c < g[0].length; c++)
if (g[r][c] == '1') { count++; sink(g, r, c); }
return count;
}
void sink(char[][] g, int r, int c) {
if (r < 0 || c < 0 || r >= g.length || c >= g[0].length || g[r][c] != '1') return;
g[r][c] = '0'; // mark visited by mutating the grid
sink(g, r + 1, c); sink(g, r - 1, c);
sink(g, r, c + 1); sink(g, r, c - 1);
}def num_islands(g):
R, C = len(g), len(g[0])
def sink(r, c):
if not (0 <= r < R and 0 <= c < C) or g[r][c] != "1":
return
g[r][c] = "0" # mark visited
for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
sink(r + dr, c + dc)
count = 0
for r in range(R):
for c in range(C):
if g[r][c] == "1":
count += 1
sink(r, c)
return countfunction numIslands(g: string[][]): number {
const R = g.length, C = g[0].length;
const sink = (r: number, c: number) => {
if (r < 0 || c < 0 || r >= R || c >= C || g[r][c] !== "1") return;
g[r][c] = "0";
sink(r + 1, c); sink(r - 1, c); sink(r, c + 1); sink(r, c - 1);
};
let count = 0;
for (let r = 0; r < R; r++)
for (let c = 0; c < C; c++)
if (g[r][c] === "1") { count++; sink(r, c); }
return count;
}Template: multi-source BFS
When "time spreads from several starting points at once" (rotting oranges, fire spreading, distance to the nearest gate), put all sources in the queue at time 0 and BFS by levels.
int orangesRotting(int[][] g) {
int R = g.length, C = g[0].length, fresh = 0, minutes = 0;
Deque<int[]> q = new ArrayDeque<>();
for (int r = 0; r < R; r++)
for (int c = 0; c < C; c++) {
if (g[r][c] == 2) q.offer(new int[]{r, c});
else if (g[r][c] == 1) fresh++;
}
int[][] dirs = {{1,0},{-1,0},{0,1},{0,-1}};
while (!q.isEmpty() && fresh > 0) {
for (int i = q.size(); i > 0; i--) { // one minute = one BFS level
int[] p = q.poll();
for (int[] d : dirs) {
int r = p[0] + d[0], c = p[1] + d[1];
if (r >= 0 && r < R && c >= 0 && c < C && g[r][c] == 1) {
g[r][c] = 2; fresh--;
q.offer(new int[]{r, c});
}
}
}
minutes++;
}
return fresh == 0 ? minutes : -1;
}from collections import deque
def oranges_rotting(g):
R, C = len(g), len(g[0])
q = deque((r, c) for r in range(R) for c in range(C) if g[r][c] == 2)
fresh = sum(row.count(1) for row in g)
minutes = 0
while q and fresh:
for _ in range(len(q)): # one minute per level
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and g[nr][nc] == 1:
g[nr][nc] = 2
fresh -= 1
q.append((nr, nc))
minutes += 1
return minutes if fresh == 0 else -1function orangesRotting(g: number[][]): number {
const R = g.length, C = g[0].length;
let q: [number, number][] = [], fresh = 0, minutes = 0;
g.forEach((row, r) => row.forEach((v, c) => (v === 2 ? q.push([r, c]) : v === 1 && fresh++)));
while (q.length && fresh) {
const next: [number, number][] = [];
for (const [r, c] of q)
for (const [nr, nc] of [[r + 1, c], [r - 1, c], [r, c + 1], [r, c - 1]])
if (nr >= 0 && nr < R && nc >= 0 && nc < C && g[nr][nc] === 1) {
g[nr][nc] = 2; fresh--; next.push([nr, nc]);
}
q = next;
minutes++;
}
return fresh === 0 ? minutes : -1;
}Reverse thinking: start from the border
"Surrounded regions" and "Pacific Atlantic water flow" are easier backwards: flood fill from the border (or from each ocean) and mark what's reachable, instead of testing every cell outward.
State-space BFS
Each state is a node; each legal move is an edge. BFS gives the minimum number of moves.
- Word ladder: words are nodes; edges connect words differing by one letter.
- Open the lock: 4-digit strings; each move turns one wheel ±1; deadends are blocked nodes.
- Sliding puzzle: the board serialised as a string.
- Shortest path visiting all nodes: state = (node, visited bitmask).
Graph construction problems
- Clone graph — BFS/DFS with a map original → copy.
- Evaluate division — build a weighted graph a → b with weight a/b; answer queries by DFS multiplying weights (or weighted Union-Find).
- Is graph bipartite — 2-colour with BFS.
- Flood Filleasy
- Number of Islandsmedium
- Max Area of Islandmedium
- Rotting Orangesmulti-source BFSmedium
- 01 Matrixmulti-source BFS from zerosmedium
- Surrounded Regionsflood from the bordermedium
- Pacific Atlantic Water Flowreverse flow from each oceanmedium
- Clone Graphmedium
- Is Graph Bipartite?medium
- Open the Lockstate BFSmedium
- Shortest Path in Binary Matrix8 directionsmedium
- Evaluate Divisionmedium
- Word Ladderhard
- Swim in Rising WaterDijkstra on max, or binary search + BFShard
- See the implicit graph: grid cells, words, or states are nodes.
- DFS/flood fill for regions; BFS for minimum steps.
- Multi-source BFS starts every source in the queue at distance 0.
- Mark visited when enqueuing; mutate the grid or keep a set.
- Prefer iterative traversal for very large grids.