Lesson 9 · Dynamic programming

Grid Dynamic Programming

When moves on a grid only go right and down, every cell's answer depends on the cell above and the cell to its left. Fill the grid in reading order and each cell is one line of arithmetic.

Grid Dynamic Programming concept diagramThree small grid corners. Count paths: 3 ways from above plus 4 from the left gives 7. Wall on the left: 3 from above plus 0 from the wall gives 3. Most collected: the cell's own 5 plus the larger neighbour 4 gives 9. Below, a 3 by 6 grid is filled row by row, left to right, so the cell above and the cell to the left are always done before the current cell.Count paths3473 + 4 = 7Wall on the left3wall · 033 + 0 = 3Most collected (cell holds 5)3495 + max(3, 4) = 9fill orderdone: greennow: bluerow by row, left to rightevery right/down route into a cell arrives from above or from the left
1

Why a Grid Is Ready-Made for DP

A grid problem asks something about routes from one cell to another: how many there are, which is cheapest, how much can be collected. If moves only go right or down, a route can never come back to a cell it left. So the cells form a one-way network, and every route into a cell arrives through a small, fixed set of neighbours.

That makes DP on grids simple to set up. The state is the cell (r, c). Its answer is built from the answers of the cells a move could have come from: the cell above and the cell to the left. Read the grid like text, row by row and left to right, and both of those are always finished before you need them.

  • State: one number per cell, the answer for routes from the start to that cell
  • Transition: combine the neighbours a move could have come from
  • Fill order: any order that finishes those neighbours first; reading order works for right/down moves
2

Count Paths in a Grid

  1. Set ways[0][0] = 1, unless the start is a wall (then the answer is 0)
  2. Go through the rows top to bottom, and each row left to right
  3. On a wall, write 0
  4. Otherwise add the value above (0 on the top row) and the value to the left (0 in the first column)
  5. The answer is the bottom-right cell

To count paths in a grid, notice that every path into (r, c) has a last move, either down from (r − 1, c) or right from (r, c − 1). No path makes both, so the counts add: ways[r][c] = ways[r − 1][c] + ways[r][c − 1]. The start has 1 way, and any cell off the grid counts as 0.

A wall is a cell no path may enter, so ways = 0 there. That 0 then feeds into the cells below and to the right, and they lose every path that would have gone through the wall. The tracer below runs this on a 3 × 4 grid with two walls; the answer is 2.

  • With no walls the count is a binomial coefficient: C(R + C − 2, R − 1), because a path is a choice of which moves are downs
  • Walls break the formula, which is why Unique Paths II needs the table and Unique Paths does not
3

Borders, Walls and the Start Cell

Most bugs in grid DP sit on the edges. A popular shortcut fills the whole first row and first column with 1 before the main loop, because along an edge there is only one way to walk. That is true without walls and wrong with them: once a wall sits on an edge, every edge cell past it has 0 ways, not 1. On the tracer's grid the shortcut gives 4 instead of 2.

The cleanest fix is to give the edges no special treatment. Treat off-grid neighbours as 0 and run the same rule on every cell, or add an extra row and column of zeros around the grid so every cell has an above and a left. Then check the two corner cases by hand: a wall on the start or on the goal means 0 paths.

  • Edges: off-grid counts as 0, so the rule needs no special case
  • Start blocked or goal blocked: answer 0
  • A 1 × 1 grid with no wall: 1 path (you are already there)
Key reference

Terms, operations, and practical uses

Key terms

  • ways[r][c]The number of right/down paths from the start to cell (r, c).
  • Fill orderThe order cells are computed; it must finish every cell's neighbours before the cell.
  • Rolling rowOne array reused for every row, reading the old value as 'above'.
Implementation

Code in Python, C++ and Java

GRID = [
    "....",
    "#.#.",
    "....",
]


def count_paths(grid):
    rows, cols = len(grid), len(grid[0])
    ways = [[0] * cols for _ in range(rows)]
    for r in range(rows):
        for c in range(cols):
            if grid[r][c] == "#":
                ways[r][c] = 0
            elif r == 0 and c == 0:
                ways[r][c] = 1
            else:
                up = ways[r - 1][c] if r > 0 else 0
                left = ways[r][c - 1] if c > 0 else 0
                ways[r][c] = up + left
    return ways


def count_paths_one_row(grid):
    cols = len(grid[0])
    row = [0] * cols
    row[0] = 1
    for line in grid:
        for c in range(cols):
            if line[c] == "#":
                row[c] = 0
            elif c > 0:
                row[c] += row[c - 1]
    return row[-1]


def border_all_ones(grid):
    rows, cols = len(grid), len(grid[0])
    ways = [[1] * cols if r == 0 else [1] + [0] * (cols - 1) for r in range(rows)]
    for r in range(1, rows):
        for c in range(1, cols):
            ways[r][c] = 0 if grid[r][c] == "#" else ways[r - 1][c] + ways[r][c - 1]
    return ways[-1][-1]


ways = count_paths(GRID)
for r, line in enumerate(GRID):
    print(line, " ".join(f"{x:>2}" for x in ways[r]))
print("paths to the bottom-right:", ways[-1][-1])
print("one rolling row:", count_paths_one_row(GRID))
print("border filled with 1s (bug):", border_all_ones(GRID))
print("no walls, 3 x 4:", count_paths(["....", "....", "...."])[-1][-1])
print("start blocked:", count_paths(["#...", "....", "...."])[-1][-1])
#include <cstdio>
#include <string>
#include <vector>
using namespace std;

typedef vector<string> Grid;
const Grid GRID = {"....", "#.#.", "...."};

vector<vector<long long>> countPaths(const Grid& g) {
    int rows = g.size(), cols = g[0].size();
    vector<vector<long long>> ways(rows, vector<long long>(cols, 0));
    for (int r = 0; r < rows; r++)
        for (int c = 0; c < cols; c++) {
            if (g[r][c] == '#') ways[r][c] = 0;
            else if (r == 0 && c == 0) ways[r][c] = 1;
            else ways[r][c] = (r > 0 ? ways[r - 1][c] : 0) + (c > 0 ? ways[r][c - 1] : 0);
        }
    return ways;
}

long long countPathsOneRow(const Grid& g) {
    int cols = g[0].size();
    vector<long long> row(cols, 0);
    row[0] = 1;
    for (const string& line : g)
        for (int c = 0; c < cols; c++) {
            if (line[c] == '#') row[c] = 0;
            else if (c > 0) row[c] += row[c - 1];
        }
    return row[cols - 1];
}

long long borderAllOnes(const Grid& g) {
    int rows = g.size(), cols = g[0].size();
    vector<vector<long long>> ways(rows, vector<long long>(cols, 0));
    for (int c = 0; c < cols; c++) ways[0][c] = 1;
    for (int r = 0; r < rows; r++) ways[r][0] = 1;
    for (int r = 1; r < rows; r++)
        for (int c = 1; c < cols; c++)
            ways[r][c] = g[r][c] == '#' ? 0 : ways[r - 1][c] + ways[r][c - 1];
    return ways[rows - 1][cols - 1];
}

int main() {
    auto ways = countPaths(GRID);
    for (size_t r = 0; r < GRID.size(); r++) {
        printf("%s", GRID[r].c_str());
        for (size_t c = 0; c < ways[r].size(); c++) printf("%s%2lld", c ? " " : " ", ways[r][c]);
        printf("\n");
    }
    printf("paths to the bottom-right: %lld\n", ways.back().back());
    printf("one rolling row: %lld\n", countPathsOneRow(GRID));
    printf("border filled with 1s (bug): %lld\n", borderAllOnes(GRID));
    printf("no walls, 3 x 4: %lld\n", countPaths({"....", "....", "...."}).back().back());
    printf("start blocked: %lld\n", countPaths({"#...", "....", "...."}).back().back());
}
public class Main {
    static final String[] GRID = {"....", "#.#.", "...."};

    static long[][] countPaths(String[] g) {
        int rows = g.length, cols = g[0].length();
        long[][] ways = new long[rows][cols];
        for (int r = 0; r < rows; r++)
            for (int c = 0; c < cols; c++) {
                if (g[r].charAt(c) == '#') ways[r][c] = 0;
                else if (r == 0 && c == 0) ways[r][c] = 1;
                else ways[r][c] = (r > 0 ? ways[r - 1][c] : 0) + (c > 0 ? ways[r][c - 1] : 0);
            }
        return ways;
    }

    static long countPathsOneRow(String[] g) {
        int cols = g[0].length();
        long[] row = new long[cols];
        row[0] = 1;
        for (String line : g)
            for (int c = 0; c < cols; c++) {
                if (line.charAt(c) == '#') row[c] = 0;
                else if (c > 0) row[c] += row[c - 1];
            }
        return row[cols - 1];
    }

    static long borderAllOnes(String[] g) {
        int rows = g.length, cols = g[0].length();
        long[][] ways = new long[rows][cols];
        for (int c = 0; c < cols; c++) ways[0][c] = 1;
        for (int r = 0; r < rows; r++) ways[r][0] = 1;
        for (int r = 1; r < rows; r++)
            for (int c = 1; c < cols; c++)
                ways[r][c] = g[r].charAt(c) == '#' ? 0 : ways[r - 1][c] + ways[r][c - 1];
        return ways[rows - 1][cols - 1];
    }

    public static void main(String[] args) {
        long[][] ways = countPaths(GRID);
        for (int r = 0; r < GRID.length; r++) {
            StringBuilder s = new StringBuilder(GRID[r]);
            for (long x : ways[r]) s.append(String.format(" %2d", x));
            System.out.println(s);
        }
        System.out.println("paths to the bottom-right: " + ways[GRID.length - 1][GRID[0].length() - 1]);
        System.out.println("one rolling row: " + countPathsOneRow(GRID));
        System.out.println("border filled with 1s (bug): " + borderAllOnes(GRID));
        System.out.println("no walls, 3 x 4: " + countPaths(new String[] {"....", "....", "...."})[2][3]);
        System.out.println("start blocked: " + countPaths(new String[] {"#...", "....", "...."})[2][3]);
    }
}
Watch it run

Step through it

Running on 3 rows x 4 columns, walls at row 1 column 0 and row 1 column 2, moves right or down

ways[r][c] = ways from above + ways from the leftwallwallstartgoalways[r][c] = ways[r − 1][c] + ways[r][c − 1], and 0 on a wallStart cell: 1 way (stand still). Off the grid counts as 0.
Step 1

The grid and the rule

Moves go right or down, and walls cannot be entered. Every path into a cell arrives from the cell above or the cell to the left, never both at once, so the two counts simply add. Filling row by row, left to right, means both neighbours are always done first.

Output
1 / 11
4

Other Questions on the Same Grid

Change what you combine and the same fill answers a different question. Counting uses +. Finding the cheapest route uses min plus the cell's cost, which is the example in two-dimensional dynamic programming. Collecting the most uses max plus the cell's value. Asking whether the goal is reachable at all uses OR.

The neighbours change with the moves. If a move may also go diagonally, add the up-left cell. In a falling path, each cell reads three cells in the row above. If moves can go in all four directions, routes can loop, and the problem stops being DP on a fixed order; it becomes a shortest-path problem for breadth-first search or Dijkstra.

Same fill order, different combine step
QuestionCell valueWall value
How many paths?above + left0
Cheapest path?cost + min(above, left)∞
Most collected?value + max(above, left)−∞
Reachable at all?above OR leftfalse
  • The wall value is whatever loses every comparison: 0 for a sum, ∞ for a min, −∞ for a max
  • Maximal Square reads above, left and up-left and takes 1 + their min
5

Space, Time and Large Counts

Each of the R × C cells does O(1) work, so time is O(R·C). The table takes O(R·C) memory, but a cell only reads the row above and the current row, so one array of length C is enough: row[c] = 0 on a wall, otherwise row[c] += row[c − 1]. Before that update, row[c] still holds the value from the row above, which is exactly the "above" term.

Counts grow fast. A 17 × 17 grid with no walls already has 601,080,390 paths, and 18 × 18 passes the 32-bit limit. Use 64-bit integers, or the modulus the problem asks for, before the numbers silently wrap.

  • One-row version loses the full table, so it cannot trace a path back; keep the table when you need the route
  • If the grid is much wider than tall, roll over columns instead and keep an array of length R
6

Grid DP Problems to Practise

These problems use the fill from this lesson with a different combine step or neighbour set. Work them in this order; each adds one idea to the last.