Leetcode Matrix Problems Are Everywhere in Interviews
Matrix and grid problems are among the most common question types in coding interviews. Whether you are applying at Google, Amazon, or any top tech company, you will almost certainly face at least one leetcode matrix problem that asks you to traverse, transform, or search a 2D array.
Here is the secret that changes everything: matrix problems are graph problems in disguise. Every cell in a grid is a node, and every adjacent cell is an edge. Once you internalize this mental model, you stop seeing scary 2D arrays and start seeing familiar graph traversal patterns that you already know.
In this guide, you will learn the three major categories of matrix interview questions — grid traversal (BFS/DFS), matrix manipulation (rotation, spiral), and dynamic programming on grids. By the end, you will have a clear framework for recognizing which pattern applies to any grid problem you encounter.
Grids as Graphs — The Mental Model That Unlocks Everything
The most important insight for grid traversal leetcode problems is seeing the grid as a graph. Each cell at position (row, col) is a node. Each adjacent cell — up, down, left, right — is a neighbor connected by an edge. In some problems, diagonal neighbors count too, giving you 8 directions instead of 4.
Once you see this, standard graph algorithms apply directly. BFS finds the shortest path on a grid. DFS explores connected components. You track visited cells the same way you track visited nodes in any graph — either with a separate set or by modifying the grid in place.
The movement pattern for 4-directional grids is so universal that you should have it memorized. Define a directions array — [[0,1],[0,-1],[1,0],[-1,0]] — and loop through it to visit all neighbors. Every grid BFS and DFS problem uses this exact pattern.
- Each cell (row, col) is a graph node
- 4-directional adjacency: up, down, left, right — 4 edges per interior cell
- 8-directional adjacency: includes diagonals — used in some problems like mines or game of life
- Boundary check: 0 <= newRow < rows && 0 <= newCol < cols before visiting a neighbor
- Visited tracking: use a Set, boolean matrix, or mark cells in-place (e.g., change "1" to "0")
Grid Traversal Patterns — BFS and DFS on 2D Arrays
Grid BFS DFS problems fall into a few recurring patterns. BFS is your go-to when the problem asks for the shortest path or minimum steps on a grid — it guarantees level-by-level exploration so the first time you reach a cell is the shortest path. DFS is better for exhaustive search, finding all connected components, or problems where you need to explore every possible path.
Flood fill is the simplest grid DFS pattern. Starting from a cell, recursively visit all connected cells with the same value and change them. This is exactly what Number of Islands (#200) does — for each unvisited "1", run DFS to mark the entire island, then increment your count.
For shortest-path problems like Rotting Oranges (#994), BFS is essential. You start by adding all rotten oranges to the queue, then process level by level. Each level represents one minute of time. When the queue is empty, the number of levels processed is your answer.
A key optimization for grid traversal is marking cells as visited in place rather than using a separate data structure. If the problem lets you modify the input grid, changing visited cells to a sentinel value saves O(m*n) space and simplifies your code.
- BFS: shortest path, minimum steps, level-order processing (Rotting Oranges #994)
- DFS: connected components, flood fill, path existence (Number of Islands #200)
- Multi-source BFS: start with multiple cells in the queue simultaneously
- In-place marking: modify grid cells to track visited status without extra space
- Backtracking on grids: restore cell state after DFS returns (Word Search #79)
Pro Tip
The 4-direction movement pattern (up, down, left, right) is so common in grid problems that you should memorize the directions array: [[0,1],[0,-1],[1,0],[-1,0]]. It saves time in every grid problem.
Matrix Manipulation — Rotate, Spiral, and Transform
Not every 2d array problem is a graph traversal. Matrix manipulation problems test your ability to work with indices, layers, and geometric transformations. These are pattern-based — once you know the trick, the implementation is straightforward.
Rotate Image (#48) asks you to rotate an n x n matrix 90 degrees clockwise in place. The elegant solution is a two-step process: first transpose the matrix (swap rows and columns), then reverse each row. This avoids the complexity of rotating elements one by one and is easy to remember.
Spiral Matrix (#54) asks you to return all elements in spiral order. The key is maintaining four boundaries — top, bottom, left, right — and shrinking them inward after processing each edge of the spiral. Walk right along the top row, down the right column, left along the bottom row, up the left column, then update boundaries.
Set Matrix Zeroes (#73) is a classic space-optimization puzzle. The naive approach uses O(m+n) space to record which rows and columns should be zeroed. The optimal solution uses the first row and first column of the matrix itself as markers, reducing extra space to O(1).
- Rotate Image (#48): transpose then reverse rows for 90-degree clockwise rotation
- Spiral Matrix (#54): four-boundary approach — top, bottom, left, right — shrink inward
- Set Matrix Zeroes (#73): use first row and column as in-place markers for O(1) space
- Transpose Matrix (#867): swap matrix[i][j] with matrix[j][i] — foundation for rotation
- Reshape Matrix (#566): flatten to 1D then fill into new dimensions using index math
Classic Grid Problems Every Candidate Should Know
Number of Islands (#200) is the gateway problem for grid BFS DFS. Given a 2D grid of "1"s (land) and "0"s (water), count the number of islands. For each unvisited "1", run BFS or DFS to mark the entire connected component, then increment your island count. Time is O(m*n), space is O(m*n) for the recursion stack or queue.
Surrounded Regions (#130) asks you to capture all "O" regions that are completely surrounded by "X". The trick is working backwards — instead of finding surrounded regions, find the unsurrounded ones. Run DFS from every "O" on the border to mark all connected "O"s as safe, then flip everything else.
Pacific Atlantic Water Flow (#417) is a harder variant where water flows from high to low elevation. Instead of BFS from every cell (which would be O((m*n)^2)), run BFS backwards from each ocean. Find cells that can reach the Pacific, find cells that can reach the Atlantic, then return the intersection.
Word Search (#79) combines grid traversal with backtracking. You DFS through the grid trying to match each character of the target word. The critical detail is marking cells as visited during your current path and unmarking them when you backtrack — otherwise you cannot reuse cells across different paths.
Industry Insight
Grid BFS/DFS problems make up roughly 15% of all coding interview questions — they combine graph traversal with 2D array manipulation, testing two skills at once.
DP on Grids — When BFS and DFS Are Not Enough
Some grid problems look like traversal problems but are actually dynamic programming problems. The key signal is when the problem asks for a count of paths, a minimum cost, or an optimal value. If you only move right and down (no cycles), DP is the right approach.
Unique Paths (#62) asks how many distinct paths exist from the top-left to the bottom-right of a grid, moving only right or down. This is pure DP: dp[i][j] = dp[i-1][j] + dp[i][j-1]. The first row and first column are all 1s because there is only one way to reach them. Time and space are both O(m*n), reducible to O(n) with a rolling array.
Minimum Path Sum (#64) is the weighted version — each cell has a cost, and you want the path from top-left to bottom-right with the smallest total. The recurrence is dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]). You can even modify the input grid in place to use O(1) extra space.
Dungeon Game (#174) is the tricky reverse DP variant. Instead of going top-left to bottom-right, you need to think backwards from the princess to the knight. dp[i][j] represents the minimum health needed at cell (i,j) to survive. You fill the table from bottom-right to top-left because the constraint propagates backwards.
- Unique Paths (#62): dp[i][j] = dp[i-1][j] + dp[i][j-1] — count paths moving right/down
- Minimum Path Sum (#64): dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1]) — optimal cost
- Dungeon Game (#174): reverse DP from bottom-right to top-left — minimum health to survive
- Signal for grid DP: "count paths," "minimum cost," movement restricted to right/down
- Space optimization: use rolling array for O(n) space or modify input grid for O(1)
Practice Strategy — How to Master Leetcode Matrix Problems
Start your matrix problem journey with Number of Islands (#200). It is the purest example of grid BFS/DFS and teaches you the foundational pattern — directions array, boundary checking, visited marking — that every other grid problem builds on. Solve it with both BFS and DFS to understand the tradeoffs.
Next, tackle Spiral Matrix (#54) to build your matrix manipulation skills. This problem is pure index management with no graph theory involved, so it exercises a different muscle. Then move to Rotting Oranges (#994) for multi-source BFS and Unique Paths (#62) for grid DP.
The biggest mistake candidates make with grid problems is defaulting to one technique. Not every grid problem is BFS/DFS, and not every grid problem is DP. Train yourself to read the problem statement carefully: shortest path means BFS, connected components means DFS, count of paths or minimum cost means DP, and geometric transformation means index manipulation.
Use YeetCode flashcards to drill the pattern recognition. When you review a grid problem, focus on identifying which category it falls into before thinking about implementation. The pattern recognition is the hard part — once you know the category, the code follows a template you have seen many times.
Common Mistake
Don't default to BFS/DFS for every grid problem — Unique Paths (#62) and Minimum Path Sum (#64) are DP problems that look like grid traversal. If the problem asks for count or minimum cost, think DP first.