Matrix and Grid Pattern: Template + 216 LeetCode Problems

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

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

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.

Matrix and Grid — Python 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.

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)

#ProblemDifficultyTopics
463Island PerimeterEasyDepth-First Search, Breadth-First Search, Array +1
566Reshape the MatrixEasyArray, Matrix, Simulation
661Image SmootherEasyArray, Matrix
733Flood FillEasyDepth-First Search, Breadth-First Search, Array +1
422Valid Word SquarePremiumEasyArray, Matrix
766Toeplitz MatrixEasyArray, Matrix
832Flipping an ImageEasyBit Manipulation, Array, Two Pointers +2
867Transpose MatrixEasyArray, Matrix, Simulation
883Projection Area of 3D ShapesEasyGeometry, Array, Math +1
892Surface Area of 3D ShapesEasyGeometry, Array, Math +1
999Available Captures for RookEasyArray, Matrix, Simulation
1030Matrix Cells in Distance OrderEasyGeometry, Array, Math +2
1260Shift 2D GridEasyArray, Matrix, Simulation
1275Find Winner on a Tic Tac Toe GameEasyArray, Hash Table, Matrix +1
1337The K Weakest Rows in a MatrixEasyArray, Binary Search, Matrix +2
1351Count Negative Numbers in a Sorted MatrixEasyArray, Binary Search, Matrix
1380Lucky Numbers in a MatrixEasyArray, Matrix
1572Matrix Diagonal SumEasyArray, Matrix
1582Special Positions in a Binary MatrixEasyArray, Matrix
1672Richest Customer WealthEasyArray, Matrix
1886Determine Whether Matrix Can Be Obtained By RotationEasyArray, Matrix
2022Convert 1D Array Into 2D ArrayEasyArray, Matrix, Simulation
2133Check if Every Row and Column Contains All NumbersEasyArray, Hash Table, Matrix
2319Check if Matrix Is X-MatrixEasyArray, Matrix
2373Largest Local Values in a MatrixEasyArray, Matrix
2500Delete Greatest Value in Each RowEasyArray, Matrix, Sorting +2
2614Prime In DiagonalEasyArray, Math, Matrix +1
2639Find the Width of Columns of a GridEasyArray, Matrix
2643Row With Maximum OnesEasyArray, Matrix
2923Find Champion IEasyArray, Matrix
2946Matrix Similarity After Cyclic ShiftsEasyArray, Math, Matrix +1
2965Find Missing and Repeated ValuesEasyArray, Hash Table, Math +1

Medium (125)

#ProblemDifficultyTopics
36Valid SudokuMediumArray, Hash Table, Matrix
48Rotate ImageMediumArray, Math, Matrix
54Spiral MatrixMediumArray, Matrix, Simulation
59Spiral Matrix IIMediumArray, Matrix, Simulation
63Unique Paths IIMediumArray, Dynamic Programming, Matrix
64Minimum Path SumMediumArray, Dynamic Programming, Matrix
73Set Matrix ZeroesMediumArray, Hash Table, Matrix
74Search a 2D MatrixMediumArray, Binary Search, Matrix
79Word SearchMediumDepth-First Search, Array, String +2
130Surrounded RegionsMediumDepth-First Search, Breadth-First Search, Union Find +2
200Number of IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
221Maximal SquareMediumArray, Dynamic Programming, Matrix
240Search a 2D Matrix IIMediumArray, Binary Search, Divide and Conquer +1
289Game of LifeMediumArray, Matrix, Simulation
304Range Sum Query 2D - ImmutableMediumDesign, Array, Matrix +1
378Kth Smallest Element in a Sorted MatrixMediumArray, Binary Search, Matrix +2
417Pacific Atlantic Water FlowMediumDepth-First Search, Breadth-First Search, Array +1
419Battleships in a BoardMediumDepth-First Search, Array, Matrix
427Construct Quad TreeMediumTree, Array, Divide and Conquer +1
498Diagonal TraverseMediumArray, Matrix, Simulation
529MinesweeperMediumDepth-First Search, Breadth-First Search, Array +1
54201 MatrixMediumBreadth-First Search, Array, Dynamic Programming +1
695Max Area of IslandMediumDepth-First Search, Breadth-First Search, Union Find +2
909Snakes and LaddersMediumBreadth-First Search, Array, Matrix
994Rotting OrangesMediumBreadth-First Search, Array, Matrix
1926Nearest Exit from Entrance in MazeMediumBreadth-First Search, Array, Matrix
2352Equal Row and Column PairsMediumArray, Hash Table, Matrix +1
286Walls and GatesPremiumMediumBreadth-First Search, Array, Matrix
308Range Sum Query 2D - MutablePremiumMediumDesign, Binary Indexed Tree, Segment Tree +2
311Sparse Matrix MultiplicationPremiumMediumArray, Hash Table, Matrix
348Design Tic-Tac-ToePremiumMediumDesign, Array, Hash Table +2
361Bomb EnemyPremiumMediumArray, Dynamic Programming, Matrix
490The MazePremiumMediumDepth-First Search, Breadth-First Search, Array +1
505The Maze IIPremiumMediumDepth-First Search, Breadth-First Search, Graph +4
531Lonely Pixel IPremiumMediumArray, Hash Table, Matrix
533Lonely Pixel IIPremiumMediumArray, Hash Table, Matrix
562Longest Line of Consecutive One in MatrixPremiumMediumArray, Dynamic Programming, Matrix
723Candy CrushPremiumMediumArray, Two Pointers, Matrix +1
750Number Of Corner RectanglesPremiumMediumArray, Math, Dynamic Programming +1
794Valid Tic-Tac-Toe StateMediumArray, Matrix
807Max Increase to Keep City SkylineMediumGreedy, Array, Matrix
835Image OverlapMediumArray, Matrix
840Magic Squares In GridMediumArray, Hash Table, Math +1
861Score After Flipping MatrixMediumGreedy, Bit Manipulation, Array +1
885Spiral Matrix IIIMediumArray, Matrix, Simulation
931Minimum Falling Path SumMediumArray, Dynamic Programming, Matrix
934Shortest BridgeMediumDepth-First Search, Breadth-First Search, Array +1
959Regions Cut By SlashesMediumDepth-First Search, Breadth-First Search, Union Find +3
1020Number of EnclavesMediumDepth-First Search, Breadth-First Search, Union Find +2
1034Coloring A BorderMediumDepth-First Search, Breadth-First Search, Array +1
1072Flip Columns For Maximum Number of Equal RowsMediumArray, Hash Table, Matrix
1091Shortest Path in Binary MatrixMediumBreadth-First Search, Array, Matrix
1102Path With Maximum Minimum ValuePremiumMediumDepth-First Search, Breadth-First Search, Union Find +4
1139Largest 1-Bordered SquareMediumArray, Dynamic Programming, Matrix
1162As Far from Land as PossibleMediumBreadth-First Search, Array, Dynamic Programming +1
1198Find Smallest Common Element in All RowsPremiumMediumArray, Hash Table, Binary Search +2
1219Path with Maximum GoldMediumArray, Backtracking, Matrix
1222Queens That Can Attack the KingMediumArray, Matrix, Simulation
1253Reconstruct a 2-Row Binary MatrixMediumGreedy, Array, Matrix
1254Number of Closed IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
1267Count Servers that CommunicateMediumDepth-First Search, Breadth-First Search, Union Find +3
1277Count Square Submatrices with All OnesMediumArray, Dynamic Programming, Matrix
1292Maximum Side Length of a Square with Sum Less than or Equal to ThresholdMediumArray, Binary Search, Matrix +1
1314Matrix Block SumMediumArray, Matrix, Prefix Sum
1329Sort the Matrix DiagonallyMediumArray, Matrix, Sorting
1391Check if There is a Valid Path in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1428Leftmost Column with at Least a OnePremiumMediumArray, Binary Search, Interactive +1
1476Subrectangle QueriesMediumDesign, Array, Matrix
1504Count Submatrices With All OnesMediumStack, Array, Dynamic Programming +2
1536Minimum Swaps to Arrange a Binary GridMediumGreedy, Array, Matrix
1559Detect Cycles in 2D GridMediumDepth-First Search, Breadth-First Search, Union Find +2
1594Maximum Non Negative Product in a MatrixMediumArray, Dynamic Programming, Matrix
1605Find Valid Matrix Given Row and Column SumsMediumGreedy, Array, Matrix
1631Path With Minimum EffortMediumDepth-First Search, Breadth-First Search, Union Find +4
1706Where Will the Ball FallMediumArray, Matrix, Simulation
1727Largest Submatrix With RearrangementsMediumGreedy, Array, Matrix +1
1730Shortest Path to Get FoodPremiumMediumBreadth-First Search, Array, Matrix
1738Find Kth Largest XOR Coordinate ValueMediumBit Manipulation, Array, Divide and Conquer +5
1765Map of Highest PeakMediumBreadth-First Search, Array, Matrix
1778Shortest Path in a Hidden GridPremiumMediumDepth-First Search, Breadth-First Search, Array +2
1810Minimum Path Cost in a Hidden GridPremiumMediumDepth-First Search, Breadth-First Search, Graph +5
1820Maximum Number of Accepted InvitationsPremiumMediumDepth-First Search, Graph, Array +1
1861Rotating the BoxMediumArray, Two Pointers, Matrix
1878Get Biggest Three Rhombus Sums in a GridMediumArray, Math, Matrix +3
1895Largest Magic SquareMediumArray, Matrix, Prefix Sum
1901Find a Peak Element IIMediumArray, Binary Search, Matrix
1905Count Sub IslandsMediumDepth-First Search, Breadth-First Search, Union Find +2
1914Cyclically Rotating a GridMediumArray, Matrix, Simulation
1937Maximum Number of Points with CostMediumArray, Dynamic Programming, Matrix
1958Check if Move is LegalMediumArray, Enumeration, Matrix
1975Maximum Matrix SumMediumGreedy, Array, Matrix
1981Minimize the Difference Between Target and Chosen ElementsMediumArray, Dynamic Programming, Matrix
1992Find All Groups of FarmlandMediumDepth-First Search, Breadth-First Search, Array +1
2017Grid GameMediumArray, Matrix, Prefix Sum
2018Check if Word Can Be Placed In CrosswordMediumArray, Enumeration, Matrix
2033Minimum Operations to Make a Uni-Value GridMediumArray, Math, Matrix +1
2061Number of Spaces Cleaning Robot CleanedPremiumMediumArray, Matrix, Simulation
2125Number of Laser Beams in a BankMediumArray, Math, String +1
2128Remove All Ones With Row and Column FlipsPremiumMediumBit Manipulation, Array, Math +1
2146K Highest Ranked Items Within a Price RangeMediumBreadth-First Search, Array, Matrix +2
2174Remove All Ones With Row and Column Flips IIPremiumMediumBit Manipulation, Breadth-First Search, Array +1
2245Maximum Trailing Zeros in a Cornered PathMediumArray, Matrix, Prefix Sum
2257Count Unguarded Cells in the GridMediumArray, Matrix, Simulation
2282Number of People That Can Be Seen in a GridPremiumMediumStack, Array, Matrix +1
2304Minimum Path Cost in a GridMediumArray, Dynamic Programming, Matrix
2326Spiral Matrix IVMediumArray, Linked List, Matrix +1
2387Median of a Row Wise Sorted MatrixPremiumMediumArray, Binary Search, Matrix
2397Maximum Rows Covered by ColumnsMediumBit Manipulation, Array, Backtracking +2
2428Maximum Sum of an HourglassMediumArray, Matrix, Prefix Sum
2482Difference Between Ones and Zeros in Row and ColumnMediumArray, Matrix, Simulation
2510Check if There is a Path With Equal Number of 0's And 1'sPremiumMediumArray, Dynamic Programming, Matrix
2536Increment Submatrices by OneMediumArray, Matrix, Prefix Sum
2545Sort the Students by Their Kth ScoreMediumArray, Matrix, Sorting
2556Disconnect Path in a Binary Matrix by at Most One FlipMediumDepth-First Search, Breadth-First Search, Array +2
2596Check Knight Tour ConfigurationMediumDepth-First Search, Breadth-First Search, Array +2
2658Maximum Number of Fish in a GridMediumDepth-First Search, Breadth-First Search, Union Find +2
2661First Completely Painted Row or ColumnMediumArray, Hash Table, Matrix
2664The Knight’s TourPremiumMediumArray, Backtracking, Matrix
2679Sum in a MatrixMediumArray, Matrix, Sorting +2
2684Maximum Number of Moves in a GridMediumArray, Dynamic Programming, Matrix
2711Difference of Number of Distinct Values on DiagonalsMediumArray, Hash Table, Matrix
2812Find the Safest Path in a GridMediumBreadth-First Search, Union Find, Array +3
2850Minimum Moves to Spread Stones Over GridMediumBreadth-First Search, Array, Dynamic Programming +1
2852Sum of Remoteness of All CellsPremiumMediumDepth-First Search, Breadth-First Search, Union Find +3
2906Construct Product MatrixMediumArray, Matrix, Prefix Sum

Hard (59)

#ProblemDifficultyTopics
37Sudoku SolverHardArray, Hash Table, Backtracking +1
85Maximal RectangleHardStack, Array, Dynamic Programming +2
174Dungeon GameHardArray, Dynamic Programming, Matrix
212Word Search IIHardTrie, Array, String +2
329Longest Increasing Path in a MatrixHardDepth-First Search, Breadth-First Search, Graph +5
363Max Sum of Rectangle No Larger Than KHardArray, Binary Search, Matrix +2
407Trapping Rain Water IIHardBreadth-First Search, Array, Matrix +1
675Cut Off Trees for Golf EventHardBreadth-First Search, Array, Matrix +1
741Cherry PickupHardArray, Dynamic Programming, Matrix
749Contain VirusHardDepth-First Search, Breadth-First Search, Array +2
778Swim in Rising WaterHardDepth-First Search, Breadth-First Search, Union Find +4
296Best Meeting PointPremiumHardArray, Math, Matrix +1
302Smallest Rectangle Enclosing Black PixelsPremiumHardDepth-First Search, Breadth-First Search, Array +2
317Shortest Distance from All BuildingsPremiumHardBreadth-First Search, Array, Matrix
499The Maze IIIPremiumHardDepth-First Search, Breadth-First Search, Graph +5
568Maximum Vacation DaysPremiumHardArray, Dynamic Programming, Matrix
631Design Excel Sum FormulaPremiumHardGraph, Design, Topological Sort +4
773Sliding PuzzleHardBreadth-First Search, Memoization, Array +3
782Transform to ChessboardHardBit Manipulation, Array, Math +1
803Bricks Falling When HitHardUnion Find, Array, Matrix
827Making A Large IslandHardDepth-First Search, Breadth-First Search, Union Find +2
864Shortest Path to Get All KeysHardBit Manipulation, Breadth-First Search, Array +1
980Unique Paths IIIHardBit Manipulation, Array, Backtracking +1
1074Number of Submatrices That Sum to TargetHardArray, Hash Table, Matrix +1
1210Minimum Moves to Reach Target with RotationsHardBreadth-First Search, Array, Matrix
1263Minimum Moves to Move a Box to Their Target LocationHardBreadth-First Search, Array, Matrix +1
1284Minimum Number of Flips to Convert Binary Matrix to Zero MatrixHardBit Manipulation, Breadth-First Search, Array +2
1289Minimum Falling Path Sum IIHardArray, Dynamic Programming, Matrix
1293Shortest Path in a Grid with Obstacles EliminationHardBreadth-First Search, Array, Matrix
1301Number of Paths with Max ScoreHardArray, Dynamic Programming, Matrix
1349Maximum Students Taking ExamHardBit Manipulation, Array, Dynamic Programming +2
1368Minimum Cost to Make at Least One Valid Path in a GridHardBreadth-First Search, Graph, Array +3
1439Find the Kth Smallest Sum of a Matrix With Sorted RowsHardArray, Binary Search, Matrix +1
1444Number of Ways of Cutting a PizzaHardMemoization, Array, Dynamic Programming +2
1463Cherry Pickup IIHardArray, Dynamic Programming, Matrix
1568Minimum Number of Days to Disconnect IslandHardDepth-First Search, Breadth-First Search, Array +2
1591Strange Printer IIHardGraph, Topological Sort, Array +1
1595Minimum Cost to Connect Two Groups of PointsHardBit Manipulation, Array, Dynamic Programming +2
1632Rank Transform of a MatrixHardUnion Find, Graph, Topological Sort +3
1728Cat and Mouse IIHardGraph, Topological Sort, Memoization +5
1970Last Day Where You Can Still CrossHardDepth-First Search, Breadth-First Search, Union Find +3
2088Count Fertile Pyramids in a LandHardArray, Dynamic Programming, Matrix
2123Minimum Operations to Remove Adjacent Ones in MatrixPremiumHardGraph, Array, Matrix
2132Stamping the GridHardGreedy, Array, Matrix +1
2258Escape the Spreading FireHardBreadth-First Search, Array, Binary Search +1
2267Check if There Is a Valid Parentheses String PathHardArray, Dynamic Programming, Matrix
2290Minimum Obstacle Removal to Reach CornerHardBreadth-First Search, Graph, Array +3
2328Number of Increasing Paths in a GridHardDepth-First Search, Breadth-First Search, Graph +5
2371Minimize Maximum Value in a GridPremiumHardUnion Find, Graph, Topological Sort +3
2392Build a Matrix With ConditionsHardGraph, Topological Sort, Array +1
2435Paths in Matrix Whose Sum Is Divisible by KHardArray, Dynamic Programming, Matrix
2503Maximum Number of Points From Grid QueriesHardBreadth-First Search, Union Find, Array +4
2573Find the String with LCPHardGreedy, Union Find, Array +3
2577Minimum Time to Visit a Cell In a GridHardBreadth-First Search, Graph, Array +3
2617Minimum Number of Visited Cells in a GridHardStack, Breadth-First Search, Union Find +5
2713Maximum Strictly Increasing Cells in a MatrixHardMemoization, Array, Hash Table +5
2732Find a Good Subset of the MatrixHardBit Manipulation, Array, Hash Table +1
2814Minimum Time Takes to Reach Destination Without DrowningPremiumHardBreadth-First Search, Array, Matrix
2931Maximum Spending After Buying ItemsHardGreedy, Array, Matrix +2

Related patterns

Problems sit in more than one pattern more often than not, and the overlap is where the interesting follow-up questions live.

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.

Meet the matrix and grid problem you did not practise

Stealth Interview is a desktop app for macOS and Windows. It reads the coding 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 is saying — while staying invisible to screen sharing.