cswork / templatesOpen the Line 500 list

STOP 14 · GRAPHS

Grid Traversal and Multisource Search

Multi-source BFS, one ring per step O(rows × cols)

Contest ratings Rating 1433–Rating 1967· median Rating 1742(4 of 15 problems rated by zerotrac)

Open the Line 500 list · stop 14 · 15 problems
Learn first
Leads to
How often asked
asked by 16 companies · in 32 reportsMeta 7, Amazon 5, Uber 3, Bloomberg 2, DoorDash 2

Warm up with this one

LC 733Flood FillEasy
Stuck? Peek at the approach

Practice visited marking through flood fill, including the case where the new and old colors are identical.

Key points

  1. Enqueue every source at the start, as if from one virtual super source; the BFS layer is the shortest distance.
  2. Mark a cell visited when it is enqueued, so it is never added twice.
  3. For connected components (island count, area) DFS or BFS both work; for the fewest steps you need BFS.

Common pitfalls

  • Marking on dequeue lets several neighbours enqueue the same cell, which times out on large grids.
  • When nothing is fresh at the start the answer is 0, not -1 and not the layer count.
  • Recursive DFS on a 1000×1000 grid overflows the stack; use BFS or an explicit stack.

Watch it run

Step through the pattern on a small example. Pause, step forwards or back, or drag the slider to any step.

Interactive demo · step by step

BFS · shortest path on a grid

How few steps from S (top left) to T (bottom right)?

S(0,0)
·(0,1)
·(0,2)
·(0,3)
·(0,4)
·(1,0)
■(1,1)
■(1,2)
·(1,3)
·(1,4)
·(2,0)
·(2,1)
■(2,2)
·(2,3)
·(2,4)
·(3,0)
·(3,1)
·(3,2)
·(3,3)
T(3,4)
CurrentDiscovered / computedAnswer
Front → back
(0,0)
Discovered
1
Current distance
—
Distance to T
not reached

S joins the queue at distance 0. Moves go up, down, left or right; dark cells are walls.

InvariantThe queue is processed in order of distance; a cell’s shortest distance is fixed when it is first discovered.

Interactive demo · step by step

DFS · counting islands on a grid

Land joined up, down, left or right is one island. How many are there?

Try your own input
1(0,0)
1(0,1)
~(0,2)
~(0,3)
1(0,4)
~(0,5)
1(1,0)
~(1,1)
~(1,2)
1(1,3)
1(1,4)
~(1,5)
~(2,0)
~(2,1)
1(2,2)
~(2,3)
~(2,4)
~(2,5)
1(3,0)
~(3,1)
1(3,2)
1(3,3)
~(3,4)
1(3,5)
CurrentDiscovered / computedAnswer
Stack bottom → top
Empty
Islands
0
Land visited
0

1 is land, ~ is water. Scan row by row; unvisited land starts a new depth-first search.

InvariantCells are marked when pushed, so each land cell enters the stack once: O(rows × columns) in all.

Template

Open one language. All four implement the same template, and each one is compiled, run and checked against test data. Then rewrite the warm-up, LC 733, with it.

Python
from collections import deque


def minutes_to_rot(grid: list[list[int]]) -> int:
    """0 empty, 1 fresh, 2 rotten. Minutes until nothing is fresh, or -1."""
    rows, cols = len(grid), len(grid[0])
    q = deque((r, c) for r in range(rows) for c in range(cols) if grid[r][c] == 2)
    fresh = sum(row.count(1) for row in grid)
    minutes = 0
    while q and fresh:
        minutes += 1
        for _ in range(len(q)):  # every rotten cell spreads one step this minute
            r, c = q.popleft()
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols and grid[nr][nc] == 1:
                    grid[nr][nc] = 2  # mark when enqueued, not when popped
                    fresh -= 1
                    q.append((nr, nc))
    return -1 if fresh else minutes
C++
// 0 empty, 1 fresh, 2 rotten. Minutes until nothing is fresh, or -1.
int minutesToRot(vector<vector<int>> grid) {
    int rows = grid.size(), cols = grid[0].size(), fresh = 0, minutes = 0;
    queue<pair<int, int>> q;
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++) {
            if (grid[r][c] == 2) q.push({r, c});
            if (grid[r][c] == 1) fresh++;
        }
    const int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
    while (!q.empty() && fresh) {
        minutes++;
        for (int k = q.size(); k > 0; k--) {  // every rotten cell spreads one step this minute
            auto [r, c] = q.front();
            q.pop();
            for (int d = 0; d < 4; d++) {
                int nr = r + dr[d], nc = c + dc[d];
                if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] != 1) continue;
                grid[nr][nc] = 2;  // mark when enqueued, not when popped
                fresh--;
                q.push({nr, nc});
            }
        }
    }
    return fresh ? -1 : minutes;
}
Java
class Solution {
    // 0 empty, 1 fresh, 2 rotten. Minutes until nothing is fresh, or -1.
    int minutesToRot(int[][] grid) {
        int rows = grid.length, cols = grid[0].length, fresh = 0, minutes = 0;
        Deque<int[]> q = new ArrayDeque<>();
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] == 2) q.offer(new int[] {r, c});
                if (grid[r][c] == 1) fresh++;
            }
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        while (!q.isEmpty() && fresh > 0) {
            minutes++;
            for (int k = q.size(); k > 0; k--) { // every rotten cell spreads one step this minute
                int[] cell = q.poll();
                for (int[] d : dirs) {
                    int nr = cell[0] + d[0], nc = cell[1] + d[1];
                    if (nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] != 1) continue;
                    grid[nr][nc] = 2; // mark when enqueued, not when popped
                    fresh--;
                    q.offer(new int[] {nr, nc});
                }
            }
        }
        return fresh > 0 ? -1 : minutes;
    }
}
Go
// minutesToRot takes 0 empty, 1 fresh, 2 rotten and returns the minutes until
// nothing is fresh, or -1.
func minutesToRot(grid [][]int) int {
	type cell struct{ r, c int }
	rows, cols := len(grid), len(grid[0])
	var q []cell
	fresh := 0
	for r := range grid {
		for c, v := range grid[r] {
			switch v {
			case 2:
				q = append(q, cell{r, c})
			case 1:
				fresh++
			}
		}
	}
	dirs := []cell{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
	minutes := 0
	for len(q) > 0 && fresh > 0 {
		minutes++
		var next []cell // every rotten cell spreads one step this minute
		for _, p := range q {
			for _, d := range dirs {
				nr, nc := p.r+d.r, p.c+d.c
				if nr < 0 || nr >= rows || nc < 0 || nc >= cols || grid[nr][nc] != 1 {
					continue
				}
				grid[nr][nc] = 2 // mark when enqueued, not when popped
				fresh--
				next = append(next, cell{nr, nc})
			}
		}
		q = next
	}
	if fresh > 0 {
		return -1
	}
	return minutes
}

Common variants

Problems at this stop also need the 2 shapes below. Open one to see when to switch to it; its code is tested in all four languages too.

Flood fill with an explicit-stack DFSO(rows × cols) time · O(rows × cols) space

To count regions, measure their area or recolour one: start from an unvisited cell and mark every same-kind cell reachable in four directions. An explicit stack instead of recursion survives huge islands, and marking on push keeps any cell from being pushed twice. LC 200 (Number of Islands), LC 695 (Max Area of Island), LC 733 (Flood Fill).

Python
def island_stats(grid: list[list[int]]) -> tuple[int, int]:
    """(number of islands, largest island area) in a 0/1 grid (LC 200, LC 695)."""
    rows, cols = len(grid), len(grid[0])
    seen = [[False] * cols for _ in range(rows)]
    count = best = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] != 1 or seen[r][c]:
                continue
            count += 1
            area, stack = 0, [(r, c)]
            seen[r][c] = True
            while stack:  # an explicit stack: no recursion limit on big islands
                i, j = stack.pop()
                area += 1
                for ni, nj in ((i + 1, j), (i - 1, j), (i, j + 1), (i, j - 1)):
                    if 0 <= ni < rows and 0 <= nj < cols and grid[ni][nj] == 1 and not seen[ni][nj]:
                        seen[ni][nj] = True  # mark on push: no cell goes in twice
                        stack.append((ni, nj))
            best = max(best, area)
    return count, best
C++
// {number of islands, largest island area} in a 0/1 grid (LC 200, LC 695).
pair<int, int> islandStats(const vector<vector<int>>& grid) {
    int rows = grid.size(), cols = grid[0].size(), count = 0, best = 0;
    vector<vector<bool>> seen(rows, vector<bool>(cols, false));
    int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++) {
            if (grid[r][c] != 1 || seen[r][c]) continue;
            count++;
            int area = 0;
            vector<pair<int, int>> stack{{r, c}};
            seen[r][c] = true;
            while (!stack.empty()) {  // an explicit stack: no recursion limit on big islands
                auto [i, j] = stack.back();
                stack.pop_back();
                area++;
                for (int d = 0; d < 4; d++) {
                    int ni = i + dr[d], nj = j + dc[d];
                    if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && grid[ni][nj] == 1 && !seen[ni][nj]) {
                        seen[ni][nj] = true;  // mark on push: no cell goes in twice
                        stack.push_back({ni, nj});
                    }
                }
            }
            best = max(best, area);
        }
    return {count, best};
}
Java
class Solution {
    // {number of islands, largest island area} in a 0/1 grid (LC 200, LC 695).
    int[] islandStats(int[][] grid) {
        int rows = grid.length, cols = grid[0].length, count = 0, best = 0;
        boolean[][] seen = new boolean[rows][cols];
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) {
                if (grid[r][c] != 1 || seen[r][c]) continue;
                count++;
                int area = 0;
                Deque<int[]> stack = new ArrayDeque<>();
                stack.push(new int[] {r, c});
                seen[r][c] = true;
                while (!stack.isEmpty()) { // an explicit stack: no recursion limit on big islands
                    int[] cell = stack.pop();
                    area++;
                    for (int[] d : dirs) {
                        int ni = cell[0] + d[0], nj = cell[1] + d[1];
                        if (ni >= 0 && ni < rows && nj >= 0 && nj < cols && grid[ni][nj] == 1 && !seen[ni][nj]) {
                            seen[ni][nj] = true; // mark on push: no cell goes in twice
                            stack.push(new int[] {ni, nj});
                        }
                    }
                }
                best = Math.max(best, area);
            }
        return new int[] {count, best};
    }
}
Go
// islandStats returns the number of islands and the largest island area in a 0/1 grid.
func islandStats(grid [][]int) (int, int) {
	rows, cols := len(grid), len(grid[0])
	seen := make([][]bool, rows)
	for r := range seen {
		seen[r] = make([]bool, cols)
	}
	count, best := 0, 0
	dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
	for r := 0; r < rows; r++ {
		for c := 0; c < cols; c++ {
			if grid[r][c] != 1 || seen[r][c] {
				continue
			}
			count++
			area := 0
			stack := [][2]int{{r, c}}
			seen[r][c] = true
			for len(stack) > 0 { // an explicit stack: no recursion limit on big islands
				cell := stack[len(stack)-1]
				stack = stack[:len(stack)-1]
				area++
				for _, d := range dirs {
					ni, nj := cell[0]+d[0], cell[1]+d[1]
					if ni >= 0 && ni < rows && nj >= 0 && nj < cols && grid[ni][nj] == 1 && !seen[ni][nj] {
						seen[ni][nj] = true // mark on push: no cell goes in twice
						stack = append(stack, [2]int{ni, nj})
					}
				}
			}
			best = max(best, area)
		}
	}
	return count, best
}
Grid BFS with state: (row, col, uses left)O(rows × cols × k) time · O(rows × cols × k) space

When moving through a grid also spends something (walls you may still break, keys in hand), the state becomes (r, c, resource), and level-by-level BFS still gives the fewest steps. Revisit a cell only when you arrive with more of the resource left than before; that pruning keeps the state count down. LC 1293 (Shortest Path in a Grid with Obstacles Elimination).

Python
from collections import deque


def shortest_with_breaks(grid: list[list[int]], k: int) -> int:
    """Fewest steps from top-left to bottom-right, breaking at most k walls (LC 1293)."""
    rows, cols = len(grid), len(grid[0])
    best = [[-1] * cols for _ in range(rows)]  # most breaks still in hand on reaching a cell
    best[0][0] = k
    q = deque([(0, 0, k)])  # a state is (r, c, breaks left)
    steps = 0
    while q:
        for _ in range(len(q)):  # one BFS level per step
            r, c, left = q.popleft()
            if r == rows - 1 and c == cols - 1:
                return steps
            for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
                if 0 <= nr < rows and 0 <= nc < cols:
                    rest = left - grid[nr][nc]
                    if rest > best[nr][nc]:  # more breaks left than any earlier visit: worth it
                        best[nr][nc] = rest
                        q.append((nr, nc, rest))
        steps += 1
    return -1
C++
// Fewest steps from top-left to bottom-right, breaking at most k walls (LC 1293).
int shortestWithBreaks(const vector<vector<int>>& grid, int k) {
    int rows = grid.size(), cols = grid[0].size();
    vector<vector<int>> best(rows, vector<int>(cols, -1));  // most breaks still in hand on reaching a cell
    best[0][0] = k;
    queue<array<int, 3>> q;  // a state is {r, c, breaks left}
    q.push({0, 0, k});
    int dr[] = {1, -1, 0, 0}, dc[] = {0, 0, 1, -1};
    for (int steps = 0; !q.empty(); steps++)
        for (int n = q.size(); n > 0; n--) {  // one BFS level per step
            auto [r, c, left] = q.front();
            q.pop();
            if (r == rows - 1 && c == cols - 1) return steps;
            for (int d = 0; d < 4; d++) {
                int nr = r + dr[d], nc = c + dc[d];
                if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
                int rest = left - grid[nr][nc];
                if (rest > best[nr][nc]) {  // more breaks left than any earlier visit: worth it
                    best[nr][nc] = rest;
                    q.push({nr, nc, rest});
                }
            }
        }
    return -1;
}
Java
class Solution {
    // Fewest steps from top-left to bottom-right, breaking at most k walls (LC 1293).
    int shortestWithBreaks(int[][] grid, int k) {
        int rows = grid.length, cols = grid[0].length;
        int[][] best = new int[rows][cols]; // most breaks still in hand on reaching a cell
        for (int[] row : best) Arrays.fill(row, -1);
        best[0][0] = k;
        Deque<int[]> q = new ArrayDeque<>(); // a state is {r, c, breaks left}
        q.offer(new int[] {0, 0, k});
        int[][] dirs = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
        for (int steps = 0; !q.isEmpty(); steps++)
            for (int n = q.size(); n > 0; n--) { // one BFS level per step
                int[] s = q.poll();
                if (s[0] == rows - 1 && s[1] == cols - 1) return steps;
                for (int[] d : dirs) {
                    int nr = s[0] + d[0], nc = s[1] + d[1];
                    if (nr < 0 || nr >= rows || nc < 0 || nc >= cols) continue;
                    int rest = s[2] - grid[nr][nc];
                    if (rest > best[nr][nc]) { // more breaks left than any earlier visit: worth it
                        best[nr][nc] = rest;
                        q.offer(new int[] {nr, nc, rest});
                    }
                }
            }
        return -1;
    }
}
Go
// shortestWithBreaks returns the fewest steps from top-left to bottom-right, breaking at most k walls.
func shortestWithBreaks(grid [][]int, k int) int {
	rows, cols := len(grid), len(grid[0])
	best := make([][]int, rows) // most breaks still in hand on reaching a cell
	for r := range best {
		best[r] = make([]int, cols)
		for c := range best[r] {
			best[r][c] = -1
		}
	}
	best[0][0] = k
	q := [][3]int{{0, 0, k}} // a state is {r, c, breaks left}
	dirs := [][2]int{{1, 0}, {-1, 0}, {0, 1}, {0, -1}}
	for steps := 0; len(q) > 0; steps++ {
		var next [][3]int // the following BFS level
		for _, s := range q {
			if s[0] == rows-1 && s[1] == cols-1 {
				return steps
			}
			for _, d := range dirs {
				nr, nc := s[0]+d[0], s[1]+d[1]
				if nr < 0 || nr >= rows || nc < 0 || nc >= cols {
					continue
				}
				if rest := s[2] - grid[nr][nc]; rest > best[nr][nc] { // more breaks left than before: worth it
					best[nr][nc] = rest
					next = append(next, [3]int{nr, nc, rest})
				}
			}
		}
		q = next
	}
	return -1
}

Why it works

  1. BFS dequeues by distance: all cells at distance d leave the queue before any at d + 1, so the layer in which a cell is first discovered is its shortest distance.
  2. Multi-source BFS is the same as starting from one virtual super source with zero-cost edges to every real source, so putting all sources in layer 0 gives each cell its distance to the nearest source.
  3. Mark cells when they are enqueued: a cell can be discovered by several neighbours in the same layer, and marking later enqueues it repeatedly, which keeps the answer but can blow up time and memory.

Say it in 30 seconds

When the interviewer asks you to talk it through: the approach, why it is correct, then the cost. One version in each language to read aloud a few times.

中文
网格最短步数我用 BFS,因为 BFS 按层扩展,一个格子第一次被发现时的层数就是最短距离。多个起点就一开始把所有起点一起入队,相当于从一个虚拟超级源点出发,算出的是到最近起点的距离。格子入队时就标记已访问,避免重复入队。每个格子最多入队一次,时间是行数乘列数。
English
For the fewest steps on a grid I use BFS, since it expands layer by layer and the layer where a cell is first found is its shortest distance. With several starting points I enqueue all of them at the start, which is like one virtual super source, and I get the distance to the nearest source. I mark a cell visited when I enqueue it so it never enters the queue twice. Each cell is enqueued at most once, so the cost is rows times columns.

Grade yourself

Grade your answer against the one above. Questions you have not mastered come back after 1, 3, 7 and 21 days, listed under My progress → Due for review. Kept on this device; sign in and it moves to your account.

Key points you covered (0 of 3)
How well did you know it?

Quick quiz

4 concept and complexity questions. Answered ones come back for spaced review along with the OA multiple-choice practice. Open the OA multiple-choice practice

4 questions
  1. Which search gives the fewest moves from start to target on an unweighted grid directly?
  2. Why does BFS usually mark a cell visited when it is enqueued rather than when it is dequeued?
  3. An R×C grid has k sources; every cell needs its distance to the nearest source. The efficient way is:
  4. The grid has R rows and C columns. What is the time complexity?
    from collections import deque
    
    def steps(grid, start):
        R, C = len(grid), len(grid[0])
        dist = {start: 0}
        q = deque([start])
        while q:
            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 grid[nr][nc] == '.' and (nr, nc) not in dist:
                    dist[(nr, nc)] = dist[(r, c)] + 1
                    q.append((nr, nc))
        return dist

Your answers stay in this browser on this device; open OA multiple-choice practice signed in to keep them in your account.

Template drills

Drills cut from the templates above: put shuffled lines back in order, fill the blanked boundary conditions back in, or write a whole template from memory in an empty editor, run against this stop's tests and compared line by line. Another one gives a new drill.

These lines are shuffled. Tap a line to pick it, then tap another to swap them, until they read as the template does; the indentation is a hint.

from collections import deque


def minutes_to_rot(grid: list[list[int]]) -> int:
    """0 empty, 1 fresh, 2 rotten. Minutes until nothing is fresh, or -1."""
                    q.append((nr, nc))
    return -1 if fresh else minutes

Practice by stage

This stop's 15 Line 500 problems in three stages: Foundation, Core and Advanced. Each has a one-line approach; try it yourself before reading it.

Foundation 4

#ProblemApproachRating
733Flood FillPractice visited marking through flood fill, including the case where the new and old colors are identical.
200Number of IslandsTreat adjacent land cells as connected components and practice DFS or BFS visited marking.
695Max Area of IslandAccumulate area during component traversal and maintain the maximum.
463Island PerimeterCount boundary contributions through four-neighbor adjacency, distinguishing water from positions outside the grid.

Core 8

#ProblemApproachRating
130Surrounded RegionsMark safe regions backward from the boundary instead of guessing whether each region is enclosed.
417Pacific Atlantic Water FlowSearch backward from each ocean and intersect the two reachable regions.
994Rotting OrangesSpread simultaneously by minute with multisource BFS and handle fresh oranges that remain unreachable.Rating 1433
286Walls and Gates 🔒Start from every gate together to fill shortest distances instead of searching separately from each room.
54201 MatrixUse multisource BFS to compute each cell's distance to the nearest zero.
1091Shortest Path in Binary MatrixFind a shortest path in an eight-neighbor grid, handling blocked starting and ending cells.Rating 1658
934Shortest BridgeMark one island, then expand outward with BFS to find the minimum flips needed to connect both islands.Rating 1826
490The Maze 🔒Use the ball's stopping positions as graph nodes rather than treating every traversed cell as a state.

Advanced 3

#ProblemApproachRating
329Longest Increasing Path in a MatrixUse strict increase to form acyclic dependencies, finding the longest path with memoized search or topological layers instead of restarting from every cell.
505The Maze II 🔒Use rolling distances as edge weights and apply shortest-path search rather than ordinary BFS layer counts.
1293Shortest Path in a Grid with Obstacles EliminationInclude remaining obstacle eliminations alongside position to model shortest paths with limited resources.Rating 1967

Core Skills

Build this stop's data structure or algorithm by hand, without libraries, judged in four languages.