Skip to content
  • Dashboard
  • Review
  • Go: plan & chat
  • Roadmap
  • Patterns & lessons49
  • Sheets
  • Problems1.5k
  • Ascend
  • Toolkit
  • Core CS + SQL
  • System Design
  • Machine Coding
  • Interview hub
  • Mock interview
  • Companies & OA
  • Leaderboard
  • Battles
  • College Cup
  • People

Keep your progress

Sync across devices with a free account.

Sign upSign in
Patterns & lessons
Sign inSign up
Patterns/Dynamic Programming

Grid / Matrix DP

O(n · m)

dp[r][c] combines the cell value with the best of the cells you could have come from.

  1. 1Learnthe lesson(you are here)
  2. 2Guidedwatch it run, line by line(not yet)
  3. 3Practisethe path, or the climb(not yet)
  4. 4Revisereviews on schedule(not yet)
Start the lesson
Learn first1D / Fibonacci-style
0%
mastery
0/19 solved
IdeaPracticeTemplatePitfalls

Recognise it

The signal

2D grid with restricted moves (right/down): count paths, min/max-cost path, largest square of ones, triangle top-to-bottom.

  1. 1Brute force

    Enumerate paths (exponential).

  2. 2The observation

    Exponential paths: each cell is a subproblem.

  3. 3Why it works

    When cell (i, j) is filled, all its predecessor cells are already final.

Reach for it when

  • +A 2-D grid with restricted moves (right/down, or 4-dir) asking count of paths or min/max-cost path.
  • +Each cell's answer depends only on a few neighbouring cells.
  • +Problems mentioning obstacles, costs, or 'reach the corner'.

Not when

  • ×Free movement in all directions with weights (shortest path)use BFS / Dijkstra, or memo DFS if strictly increasing
  • ×Connectivity/region question (islands)use Graph traversal
  • ×Path must avoid revisiting cells under arbitrary movementuse Search / backtracking
  • ×Two walkers interact (Cherry Pickup)use Joint-state DP over both walkers

Intuition

Grid DP answers "how many paths?" or "cheapest path?" through a 2-D board where you move in fixed directions (usually right or down). dp[r][c] = the answer for the cell at (r, c). Since you can only arrive at a cell from the cells that point into it, each cell combines its neighbours.

Read the full intuition

Unique Paths (count, only right/down): to stand on (r,c) you came from above or from the left, so dp[r][c] = dp[r-1][c] + dp[r][c-1]. The top row and left column are all 1 (only one straight-line way to reach them). Fill row by row; bottom-right holds the total.

Minimum Path Sum (cost): same neighbours, but you optimise instead of count — dp[r][c] = grid[r][c] + min(dp[r-1][c], dp[r][c-1]). Add the current cell's cost to the cheaper way in.

The whole family follows one recipe:

  1. dp[r][c] = best/count to reach (r,c).
  2. Combine the cells you could have come from (up, left — and diagonally for some).
  3. Seed the first row/column carefully, read the answer at the far corner.

Key idea

Two twists worth knowing: obstacles set a cell's dp to 0 (no path through a wall); Dungeon Game fills backwards from the bottom-right because the constraint (health > 0) applies at the end, so you propagate the requirement upstream.

Why it costs what it costs

Time O(R·C). each grid cell is computed once in O(1) from its neighbours.

Space O(R·C). the dp grid; reducible to O(C) by keeping a single rolling row (each cell needs only the row above and the left neighbour).

Practice

Next · Foundation

Unique Paths

dp[i][j] = up + left (also C(m+n-2, m-1)).

0/19 solved
  • Unique PathsFoundationFoundationJane StreetMedium
  • Unique Paths IIApply it · Obstacles.Apply itMedium
  • Minimum Path SumOne change · Optimise cost.One changeMedium
  • TriangleOne change · Irregular shape.One changeMedium
  • Dungeon GameTwists · Constraint on the running minimum.TwistsHard
  • Maximal SquareBranches · DP value is a size, not a path.BranchesMedium
  • Maximal RectangleCombine · Rectangles, not squares.CombineGoogle, AmazonHard
  • Grid Paths IAdvanced · Counting with mod at scale.AdvancedCSESMedium
  • Cherry PickupMastery checkMastery checkHard
  • Minimal Grid PathCSESHard
  • Filled Subgrid Count ICSESMedium
  • Filled Subgrid Count IICSESHard

Pitfalls

Classic bugs

  • !First row/column have one incoming direction; generic min(up,left) indexes out of bounds there.
  • !Python [[0]*C]*R aliases rows; build with a comprehension.
  • !Obstacles: a blocked cell's dp is 0; a blocked start means the answer is 0.
  • !Maximal Square stores side length: min(top, left, diag)+1, only on a '1' cell.
  • !Dungeon Game fills bottom-right to top-left, clamping health to >= 1; the constraint is on the running minimum, so a forward fill is wrong.

Looks like it, isn't

  • Longest Increasing Path in a Matrix needs Topological Sort
    Why
    Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.
  • Soup Servings needs Probability & Expected-Value DP (linearity of expectation)
    Why
    n goes up to 1e9, but the editorial notes the probability tends to 1, so cap n and run the small DP. source ↗
Go deepervariants and techniques · 2 combinations · resources

Variants and techniques

  • Count pathsdp[r][c] = dp[r-1][c] + dp[r][c-1]; edges = 1. Unique Paths.
  • Paths with obstaclesSame, but a wall cell → dp 0. Unique Paths II.
  • Min/max cost pathdp = cell + min/max(up, left). Minimum Path Sum, Triangle.
  • Square of 1sdp[r][c] = min(top,left,diag)+1 on a 1-cell; track max side. Maximal Square.
  • Backward fillConstraint applies at the end → propagate from the goal cell upstream. Dungeon Game.

Combinations

  • Monotonic Stack+Grid / Matrix DP

    largest all-ones rectangle in a binary matrix

    Monotonic Stack:
    largest rectangle in each histogram
    Grid / Matrix DP:
    builds column heights row by row

    Maximal RectangleMaximum Building I

  • Grid / Matrix DP+Prefix Sum

    row DP where moving between columns costs |j - k|

    Grid / Matrix DP:
    row-by-row DP
    Prefix Sum:
    left-to-right and right-to-left running maxima of prev[k] +/- k remove the |j - k| term

    Maximum Number of Points with Cost

Resources

  • DP lecture notesErrichto · video
  • AtCoder Educational DP ContestAtCoder · sheet
  • Introduction to DPUSACO Guide · course
  • Dynamic Programming PatternsLeetCode discuss · article
  • Dynamic Programming playlistAditya Verma · video
  • Bitmask DPUSACO Guide · course
  • Digit DPCodeforces · blog
Palindromic SubstringsInterval DP
TodayReviewPatternsProblems

Template · clean C++, Java and Python to revise from

Start the free 7-day trial