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

Learn the pattern · ~15 min

Grid / Matrix DP

also called paths on grids

When moves only go one way (right or down), a cell's best answer depends only on the cells it can be entered from, so fill the grid in an order where those are always done first, and each cell is solved once.

Signalscount/min-cost paths with restricted moveslargest square/rectangle of onestriangle top-to-bottomLearn first1D / Fibonacci-style
Cheat sheet and practice

Reach for it when you read

  • +A grid where moves go only right and down (or only to the next row): count the routes, or find the cheapest or best one.
  • +"Pick one cell per row" with a rule tying each pick to the row above: falling paths, a triangle.
  • +A cell's answer is built from a fixed few neighbours already solved: the largest square of 1s ending here.
  • +The brute force tries every path, and many paths pass through the same cell.

Not this one when

  • ×Moves in all four directions with a fewest-steps question: BFS (Dijkstra with weights). Paths can loop back, so there's no fill order.
  • ×"Is there a path?" or "count the islands": a flood fill with DFS/BFS, no DP.
  • ×Routes in an empty R × C grid: the formula C(R + C − 2, R − 1) answers it directly.

Learn Grid / Matrix DP

First, what is DP on a grid?

DP (dynamic programming) means: solve each small question once, write the answer down, and build bigger answers out of the written ones.

On a grid, the small questions are the cells. If you may only move right or down, a cell is entered from only two places: above it, or its left. Fill row by row, left to right, and both are ready when you need them.

Counting routes, cell by cell

How many right/down routes lead from the top-left corner of a 3 × 4 grid to each cell? The rule is one line:

A cell's count = the count of the cell above + the count of the cell to the left.

The top row and the left column can only be reached in a straight line, so each of them has exactly 1.

cell what happens routes
row 0, and column 0 a straight line is the only way in 1 each
(1, 1) 1 from above + 1 from the left 2
(1, 2) 1 from above + 2 from the left 3
(1, 3) 1 + 3 4
(2, 1) 2 from above + 1 from the left 3
(2, 2) 3 + 3 6
(2, 3) 4 + 6 10

No cell was counted twice: when (2, 3) asked for (1, 3) and (2, 2), both were already written.

The code for it

C++
vector<vector<long long>> ways(R, vector<long long>(C, 1));   // first row and column: 1
for (int r = 1; r < R; r++)
    for (int c = 1; c < C; c++)
        ways[r][c] = ways[r - 1][c] + ways[r][c - 1];          // from above + from the left

You don't need to memorise this. It's the table above: start everything at 1, then every inner cell adds its two ways in.

Why this loop order? A cell only reads up and left, and row by row, left to right, those are filled first. The fill order must follow the direction the moves come from.

Fine, but how does this help us?

Here's a classic problem: Minimum Path Sum. Each cell has a cost. Walk from the top-left to the bottom-right, moving only right or down, and make the total cost of the cells you step on as small as possible.

Text
4 5 4
2 6 3
5 8 1

A 3 × 3 grid has only six routes, so try them all:

route cells total
RRDD 4 → 5 → 4 → 3 → 1 17
RDRD 4 → 5 → 6 → 3 → 1 19
RDDR 4 → 5 → 6 → 8 → 1 24
DRRD 4 → 2 → 6 → 3 → 1 16
DRDR 4 → 2 → 6 → 8 → 1 21
DDRR 4 → 2 → 5 → 8 → 1 20

The answer is 16: 4 → 2 → 6 → 3 → 1. Grabbing the cheaper next cell each time fails: 4 → 2 → 5 → 8 → 1 = 20.

The brute force

The choices: the last step into a cell came from above or from the left. So ask "what's the cheapest way into (r, c)?" and try both.

C++
int best(int r, int c) {                   // cheapest way into (r, c)
    if (r == 0 && c == 0) return g[0][0];
    if (r == 0) return g[r][c] + best(r, c - 1);     // top row: only from the left
    if (c == 0) return g[r][c] + best(r - 1, c);     // left column: only from above
    return g[r][c] + min(best(r - 1, c), best(r, c - 1));
}
// answer: best(R - 1, C - 1)

Draw the calls for the corner (2, 2), small:

  • best(2,2)
    • from above: best(1,2)
      • best(0,2) → best(0,1) → best(0,0)
      • best(1,1)
        • best(0,1) → best(0,0)
        • best(1,0) → best(0,0)
    • from the left: best(2,1)
      • best(1,1)← the same cell again
        • best(0,1) → best(0,0)
        • best(1,0) → best(0,0)
      • best(2,0) → best(1,0) → best(0,0)

That's 19 calls for 9 cells, and the start (0, 0) is reached 6 times, once per route. In general the start is reached once for every route, so this is trying every path. Already a 17 × 17 grid takes 1.6 s; a 200 × 200 grid has about 2.6 × 10¹¹⁸ routes. Time limit exceeded.

The one thought: the same cell comes back

Point at best(1,1) in the tree. It's solved twice: once under "from above", once under "from the left".

Does the cheapest way into (1, 1) depend on where you go after it? No. Whether the walk continues right to (1, 2) or down to (2, 1), the cheapest way to reach (1, 1) is the same number: 4 → 2 → 6, cost 12. The question depends only on the cell.

So there are only R · C different questions, one per cell. The 19 calls are 9 questions with repeats. Answer each cell once.

Memoise it

C++
int bestMemo(int r, int c) {               // memo starts as all -1
    if (memo[r][c] != -1) return memo[r][c];         // this cell is done: reuse it
    int from;
    if (r == 0 && c == 0) from = 0;
    else if (r == 0) from = bestMemo(r, c - 1);
    else if (c == 0) from = bestMemo(r - 1, c);
    else from = min(bestMemo(r - 1, c), bestMemo(r, c - 1));
    return memo[r][c] = g[r][c] + from;
}

The bottom-up table

A cell only needs up and left, so drop the recursion and fill in reading order, like the route count.

C++
vector<vector<int>> dp(R, vector<int>(C));
for (int r = 0; r < R; r++)
    for (int c = 0; c < C; c++) {
        if (r == 0 && c == 0) dp[r][c] = g[0][0];
        else if (r == 0) dp[r][c] = g[r][c] + dp[r][c - 1];    // top row: only from the left
        else if (c == 0) dp[r][c] = g[r][c] + dp[r - 1][c];    // left column: only from above
        else dp[r][c] = g[r][c] + min(dp[r - 1][c], dp[r][c - 1]);
    }
// answer: dp[R - 1][C - 1]

Dry run

Same grid. Each cell is its own cost plus the cheaper of the two cells it can come from.

c0 c1 c2
r0 4 4 + 5 = 9 9 + 4 = 13
r1 4 + 2 = 6 6 + min(9, 6) = 12 3 + min(13, 12) = 15
r2 6 + 5 = 11 8 + min(12, 11) = 19 1 + min(15, 19) = 16

dp[2][2] = 16, the same answer as the brute force. Follow the min choices backwards from 16 and you get the path: 15 came from 12, 12 from 6, 6 from 4.

Why it's O(R · C)

Count cells, not loops: each is filled once and reads two others. So O(R · C) time and space: 40,000 cells for 200 × 200.

From 2.6 × 10¹¹⁸ routes down to 40,000 cells, by answering each cell once.

Only need the last row? Keep one row

A cell reads the row above and its left neighbour, nothing older. So one array of length C is enough: before you overwrite row[c], it still holds the value from above.

C++
row[c] = g[r][c] + min(row[c], row[c - 1]);   // inner cells (r, c >= 1); row[c] is still "above"

On our grid the row goes 4 9 13, then 6 12 15, then 11 19 16. Space drops to O(C).

Obstacles? A blocked cell is 0

Unique Paths II blocks some cells. A blocked cell has 0 routes, so the edges are no longer all 1: past a block, the edge is cut off.

C++
if (blocked[r][c]) ways[r][c] = 0;            // nothing passes through here

Block (1, 1) in the 3 × 4 grid and the corner drops from 10 to 4.

A triangle? Fill from the bottom up

In Triangle, each cell has two children below it; find the cheapest path from the top to the bottom row. Start from the bottom and fold upwards:

C++
dp[c] = t[r][c] + min(dp[c], dp[c + 1]);      // the two cells below

For 3 / 6 2 / 1 8 5 / 4 7 3 6, the rows fold to 5 11 8, then 11 10, then 13: 3 → 2 → 5 → 3.

A shape, not a path? Same neighbours

Maximal Square: dp[r][c] = the side of the biggest square of 1s with its bottom-right corner at (r, c). The smallest of its three neighbours limits it:

C++
if (m[r][c] == 1) dp[r][c] = 1 + min({dp[r - 1][c], dp[r][c - 1], dp[r - 1][c - 1]});

For the rows 1101 / 1111 / 0111 / 1111 the biggest square has side 3.

Remember this

  • Moves go one way only → a cell depends on a fixed few neighbours. Fill so those come first.
  • If moves can go in all four directions, there's no fill order: it's a shortest-path problem (BFS, Dijkstra), not a grid DP.
  • Trap: the edges. The top row and left column have only one way in; handle them before the min.
  • Trap: the cheapest next step is not the cheapest path.
  • Whenever a problem walks a grid right/down (or row to row) and asks for a count, a cheapest or a best, it's this table.

Practise it on Unique Paths, then Unique Paths II (blocked cells), Minimum Path Sum, Triangle (fill from the bottom), Maximal Square (a shape) and Dungeon Game (fill from the goal back).

Watch it work, line by line

Minimum Path Sum ↗, grid = [[1,3,1],[1,5,1],[4,2,1]] → 7 (1 → 3 → 1 → 1 → 1). Step with → and ←. The data is on the left, the code and the variables that changed on the right, and 3 times it stops to ask you what happens next.

Loading the walkthrough…

When to use it, and when not

Ask yourself

Can I only move in fixed directions (right/down, or down a triangle), so that every cell depends only on cells I can fill before it?

Reach for it when

  • +count/min-cost paths with restricted moves
  • +largest square/rectangle of ones
  • +triangle top-to-bottom
  • +R*C up to ~1e6

It fails 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

Looks like it, isn't (and the other way round)

  • Longest Increasing Path in a Matrix looks like Grid / Matrix DP, needs Topological Sort

    Moves go in four directions, so there is no row-major order; the strict increase makes a DAG for memo DFS / Kahn.

  • Soup Servings looks like Grid / Matrix DP, needs Probability & Expected-Value DP (linearity of expectation)

    n goes up to 1e9, but the editorial notes the probability tends to 1, so cap n and run the small DP.

Recall card

Answer each one out loud before you open it. Come back in three days and try again without reading the page.

  • 1Why fill row by row, left to right?Reveal

    Each cell needs the cell above and the cell on its left. That order finishes both before it.

  • 2What's special about the first row and first column?Reveal

    They have only one way in (from the left, or from above). A generic min(up, left) reads outside the grid there.

  • 3When do you fill from the goal backwards?Reveal

    When the rule is about the rest of the route, like health that must stay positive the whole way (Dungeon Game).

  • 4The brute-force search carried "total so far". Why couldn't you just cache it?Reveal

    Calls with different totals look different, so nothing repeats. Ask the question that ignores the past instead (cheapest from the start to this cell), and the repeats become identical subproblems you can store.

Practice ladder

every problem →
  1. 1Unique Pathscount the routesMedium
  2. 2Unique Paths IIobstaclesMedium
  3. 3Minimum Path Sumthe hookMedium
  4. 4Trianglebottom-upMedium
  5. 5Grid Paths Icount with trapsMedium
  6. 6Maximal Squarea shapeMedium
  7. 7Dungeon Gamebackward fillHard
  8. 8Cherry Pickuptwo walkersHard

Finished Grid / Matrix DP? Mark it done and Lessgo moves you to the next step.

Start the climb9 steps from E-Rank to S, with a coachPractise itthe cheat sheet and every problem, easy to OA level
Back to Grid / Matrix DP

On this page

The lessonWatch it workThe templateWhen to use itRecallPractice ladder
TodayReviewPatternsProblems

The template: frame and slot · every line explained, then clean C++, Java and Python to revise from

Start the free 7-day trial