Pattern 13 of 22

Matrix and Grid Pattern: Template + 216 LeetCode Problems

Treat a 2-D grid as a graph whose neighbours are the four adjacent cells.

Easy
32
Medium
125
Hard
59
Time
O(r · c)

What the matrix and grid pattern is

A grid is a graph that nobody bothered to build: each cell is a node and its neighbours are the adjacent cells, so DFS, BFS and union-find all apply unchanged once you write the neighbour loop as a list of offsets rather than four copied blocks. Flood fill — walk from a cell, claim everything connected to it, repeat from every unclaimed cell — is the shape behind counting islands, enclosing regions and colouring components. Marking visited cells in the grid itself, by overwriting them, saves the extra structure and is usually acceptable; when it is not, a set of coordinate tuples is the fallback. The bounds check belongs at the top of the recursive call rather than before it, so there is one copy of it instead of four. Rotation and spiral problems are a different sub-family: they are index arithmetic, and the reliable way through them is to name the boundaries explicitly — top, bottom, left, right — and shrink them, rather than trying to derive a closed-form index map under pressure.

When to use it

  • Cells are connected to their neighbours and you need regions, components or reachability.
  • The shortest path through a grid is wanted, which is BFS with four or eight offsets.
  • The answer is a distance from the nearest of many sources — one multi-source BFS pass.
  • The problem is index mechanics: rotate in place, traverse in spiral order, transpose.

The matrix and grid template in Python

The shape, not a solution to any one problem. Adapt the condition and the summary being maintained; the skeleton stays the same across the 216 problems listed below.

PythonMatrix and Grid template
def count_islands(grid):
    rows, cols = len(grid), len(grid[0])

    def sink(r, c):
        if not (0 <= r < rows and 0 <= c < cols) or grid[r][c] != "1":
            return                          # one bounds check, not four
        grid[r][c] = "0"                    # mark in place; no separate seen set
        for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
            sink(r + dr, c + dc)

    islands = 0
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "1":
                islands += 1
                sink(r, c)

    return islands

Complexity characteristics

Time
O(r · c)
Auxiliary space
O(r · c) worst case, O(1) when marking in place

Flood fill visits every cell at most once across all of its starting points, because a claimed cell is never re-entered — so counting islands is linear in the number of cells even though it launches a traversal from many of them. The space is the stack or queue, which can hold every cell on a grid that is one large region. Overwriting visited cells in the grid itself removes the separate seen structure entirely, at the cost of destroying the input.

Eyes only

Meet the matrix and grid problem you did not practise.

In the live round, Stealth Interview reads the problem off your screen, returns a working solution with a step-by-step explanation and its time and space complexity, and transcribes what the interviewer says. It's a desktop app for macOS and Windows, invisible to screen sharing.

All 216 matrix and grid LeetCode problems

Every problem in the library the matrix and grid pattern applies to, grouped by LeetCode's own difficulty rating. 178 of the 216 carry a complete Python solution with a worked example and complexity analysis; the rest are listed for completeness, with the LeetCode Premium ones marked.

Related LeetCode topics

Easy (32)

Easy problems
No.Problem
0463Island Perimeter
0566Reshape the Matrix
0661Image Smoother
0733Flood Fill
0422Valid Word SquarePremium
0766Toeplitz Matrix
0832Flipping an Image
0867Transpose Matrix
0883Projection Area of 3D Shapes
0892Surface Area of 3D Shapes
0999Available Captures for Rook
1030Matrix Cells in Distance Order
1260Shift 2D Grid
1275Find Winner on a Tic Tac Toe Game
1337The K Weakest Rows in a Matrix
1351Count Negative Numbers in a Sorted Matrix
1380Lucky Numbers in a Matrix
1572Matrix Diagonal Sum
1582Special Positions in a Binary Matrix
1672Richest Customer Wealth
1886Determine Whether Matrix Can Be Obtained By Rotation
2022Convert 1D Array Into 2D Array
2133Check if Every Row and Column Contains All Numbers
2319Check if Matrix Is X-Matrix
2373Largest Local Values in a Matrix
2500Delete Greatest Value in Each Row
2614Prime In Diagonal
2639Find the Width of Columns of a Grid
2643Row With Maximum Ones
2923Find Champion I
2946Matrix Similarity After Cyclic Shifts
2965Find Missing and Repeated Values

Medium (125)

Medium problems
No.Problem
0036Valid Sudoku
0048Rotate Image
0054Spiral Matrix
0059Spiral Matrix II
0063Unique Paths II
0064Minimum Path Sum
0073Set Matrix Zeroes
0074Search a 2D Matrix
0079Word Search
0130Surrounded Regions
0200Number of Islands
0221Maximal Square
0240Search a 2D Matrix II
0289Game of Life
0304Range Sum Query 2D - Immutable
0378Kth Smallest Element in a Sorted Matrix
0417Pacific Atlantic Water Flow
0419Battleships in a Board
0427Construct Quad Tree
0498Diagonal Traverse
0529Minesweeper
054201 Matrix
0695Max Area of Island
0909Snakes and Ladders
0994Rotting Oranges
1926Nearest Exit from Entrance in Maze
2352Equal Row and Column Pairs
0286Walls and GatesPremium
0308Range Sum Query 2D - MutablePremium
0311Sparse Matrix MultiplicationPremium
0348Design Tic-Tac-ToePremium
0361Bomb EnemyPremium
0490The MazePremium
0505The Maze IIPremium
0531Lonely Pixel IPremium
0533Lonely Pixel IIPremium
0562Longest Line of Consecutive One in MatrixPremium
0723Candy CrushPremium
0750Number Of Corner RectanglesPremium
0794Valid Tic-Tac-Toe State
0807Max Increase to Keep City Skyline
0835Image Overlap
0840Magic Squares In Grid
0861Score After Flipping Matrix
0885Spiral Matrix III
0931Minimum Falling Path Sum
0934Shortest Bridge
0959Regions Cut By Slashes
1020Number of Enclaves
1034Coloring A Border
1072Flip Columns For Maximum Number of Equal Rows
1091Shortest Path in Binary Matrix
1102Path With Maximum Minimum ValuePremium
1139Largest 1-Bordered Square
1162As Far from Land as Possible
1198Find Smallest Common Element in All RowsPremium
1219Path with Maximum Gold
1222Queens That Can Attack the King
1253Reconstruct a 2-Row Binary Matrix
1254Number of Closed Islands
1267Count Servers that Communicate
1277Count Square Submatrices with All Ones
1292Maximum Side Length of a Square with Sum Less than or Equal to Threshold
1314Matrix Block Sum
1329Sort the Matrix Diagonally
1391Check if There is a Valid Path in a Grid
1428Leftmost Column with at Least a OnePremium
1476Subrectangle Queries
1504Count Submatrices With All Ones
1536Minimum Swaps to Arrange a Binary Grid
1559Detect Cycles in 2D Grid
1594Maximum Non Negative Product in a Matrix
1605Find Valid Matrix Given Row and Column Sums
1631Path With Minimum Effort
1706Where Will the Ball Fall
1727Largest Submatrix With Rearrangements
1730Shortest Path to Get FoodPremium
1738Find Kth Largest XOR Coordinate Value
1765Map of Highest Peak
1778Shortest Path in a Hidden GridPremium
1810Minimum Path Cost in a Hidden GridPremium
1820Maximum Number of Accepted InvitationsPremium
1861Rotating the Box
1878Get Biggest Three Rhombus Sums in a Grid
1895Largest Magic Square
1901Find a Peak Element II
1905Count Sub Islands
1914Cyclically Rotating a Grid
1937Maximum Number of Points with Cost
1958Check if Move is Legal
1975Maximum Matrix Sum
1981Minimize the Difference Between Target and Chosen Elements
1992Find All Groups of Farmland
2017Grid Game
2018Check if Word Can Be Placed In Crossword
2033Minimum Operations to Make a Uni-Value Grid
2061Number of Spaces Cleaning Robot CleanedPremium
2125Number of Laser Beams in a Bank
2128Remove All Ones With Row and Column FlipsPremium
2146K Highest Ranked Items Within a Price Range
2174Remove All Ones With Row and Column Flips IIPremium
2245Maximum Trailing Zeros in a Cornered Path
2257Count Unguarded Cells in the Grid
2282Number of People That Can Be Seen in a GridPremium
2304Minimum Path Cost in a Grid
2326Spiral Matrix IV
2387Median of a Row Wise Sorted MatrixPremium
2397Maximum Rows Covered by Columns
2428Maximum Sum of an Hourglass
2482Difference Between Ones and Zeros in Row and Column
2510Check if There is a Path With Equal Number of 0's And 1'sPremium
2536Increment Submatrices by One
2545Sort the Students by Their Kth Score
2556Disconnect Path in a Binary Matrix by at Most One Flip
2596Check Knight Tour Configuration
2658Maximum Number of Fish in a Grid
2661First Completely Painted Row or Column
2664The Knight’s TourPremium
2679Sum in a Matrix
2684Maximum Number of Moves in a Grid
2711Difference of Number of Distinct Values on Diagonals
2812Find the Safest Path in a Grid
2850Minimum Moves to Spread Stones Over Grid
2852Sum of Remoteness of All CellsPremium
2906Construct Product Matrix

Hard (59)

Hard problems
No.Problem
0037Sudoku Solver
0085Maximal Rectangle
0174Dungeon Game
0212Word Search II
0329Longest Increasing Path in a Matrix
0363Max Sum of Rectangle No Larger Than K
0407Trapping Rain Water II
0675Cut Off Trees for Golf Event
0741Cherry Pickup
0749Contain Virus
0778Swim in Rising Water
0296Best Meeting PointPremium
0302Smallest Rectangle Enclosing Black PixelsPremium
0317Shortest Distance from All BuildingsPremium
0499The Maze IIIPremium
0568Maximum Vacation DaysPremium
0631Design Excel Sum FormulaPremium
0773Sliding Puzzle
0782Transform to Chessboard
0803Bricks Falling When Hit
0827Making A Large Island
0864Shortest Path to Get All Keys
0980Unique Paths III
1074Number of Submatrices That Sum to Target
1210Minimum Moves to Reach Target with Rotations
1263Minimum Moves to Move a Box to Their Target Location
1284Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
1289Minimum Falling Path Sum II
1293Shortest Path in a Grid with Obstacles Elimination
1301Number of Paths with Max Score
1349Maximum Students Taking Exam
1368Minimum Cost to Make at Least One Valid Path in a Grid
1439Find the Kth Smallest Sum of a Matrix With Sorted Rows
1444Number of Ways of Cutting a Pizza
1463Cherry Pickup II
1568Minimum Number of Days to Disconnect Island
1591Strange Printer II
1595Minimum Cost to Connect Two Groups of Points
1632Rank Transform of a Matrix
1728Cat and Mouse II
1970Last Day Where You Can Still Cross
2088Count Fertile Pyramids in a Land
2123Minimum Operations to Remove Adjacent Ones in MatrixPremium
2132Stamping the Grid
2258Escape the Spreading Fire
2267Check if There Is a Valid Parentheses String Path
2290Minimum Obstacle Removal to Reach Corner
2328Number of Increasing Paths in a Grid
2371Minimize Maximum Value in a GridPremium
2392Build a Matrix With Conditions
2435Paths in Matrix Whose Sum Is Divisible by K
2503Maximum Number of Points From Grid Queries
2573Find the String with LCP
2577Minimum Time to Visit a Cell In a Grid
2617Minimum Number of Visited Cells in a Grid
2713Maximum Strictly Increasing Cells in a Matrix
2732Find a Good Subset of the Matrix
2814Minimum Time Takes to Reach Destination Without DrowningPremium
2931Maximum Spending After Buying Items

Matrix and Grid pattern FAQ

What is the matrix and grid pattern?

A grid is a graph that nobody bothered to build: each cell is a node and its neighbours are the adjacent cells, so DFS, BFS and union-find all apply unchanged once you write the neighbour loop as a list of offsets rather than four copied blocks.

How many LeetCode problems use the matrix and grid pattern?

This page lists 216 LeetCode problems that the matrix and grid pattern applies to: 32 Easy, 125 Medium and 59 Hard. 178 of them carry a complete Python solution with complexity analysis.

What is the time complexity of the matrix and grid pattern?

O(r · c) time and O(r · c) worst case, O(1) when marking in place space. Flood fill visits every cell at most once across all of its starting points, because a claimed cell is never re-entered — so counting islands is linear in the number of cells even though it launches a traversal from many of them. The space is the stack or queue, which can hold every cell on a grid that is one large region. Overwriting visited cells in the grid itself removes the separate seen structure entirely, at the cost of destroying the input.

When should I use the matrix and grid pattern in an interview?

Cells are connected to their neighbours and you need regions, components or reachability. The shortest path through a grid is wanted, which is BFS with four or eight offsets.

Which matrix and grid problem should I start with?

LeetCode 422. Valid Word Square is the lowest-numbered Easy problem on this page, which makes it the usual starting point: the technique is visible without the problem's own complications getting in the way.

What patterns are related to matrix and grid?

Depth-First Search, Breadth-First Search, Union-Find, Dynamic Programming. Problems frequently sit in more than one of these, and the overlap is where the interesting follow-up questions come from.

More ways in: all 22 patterns, the curated study lists, or the full problem list.