Graph Patterns (Grids, Islands, BFS & DFS)

Flood fill, counting islands, multi-source BFS, shortest paths in grids, and cloning — the graph problems interviews love.

Intermediate 2 min readLesson 13 of 25

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.

When to use this pattern
  • 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);
}

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.

Rotting oranges
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;
}

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.
Practice problems
  • 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
Key takeaways
  • 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.