Fill a grid of states row by row for paths, costs, triangles, falling paths and the largest square, keeping one row when that is enough.
You work on a game app with a treasure map. The map is a grid of cells, and each cell holds a score: treasure is positive, and a hazard is negative. A player starts in the top left cell and walks to the bottom right cell. Every move goes one cell right or one cell down.
Your team lead says: "Which route earns the highest total score? Every cell on the route counts, the first and the last included."
Start with a small map of three rows and three columns. Its scores are [[2, -3, 4], [1, 5, -2], [-1, 3, 6]].
There are 6 routes, and you can list them. D means down and R means right.
| Moves | Cells visited | Total |
|---|---|---|
| D D R R | 2 + 1 + -1 + 3 + 6 | 11 |
| D R D R | 2 + 1 + 5 + 3 + 6 | 17 |
| D R R D | 2 + 1 + 5 + -2 + 6 | 12 |
| R D D R | 2 + -3 + 5 + 3 + 6 | 13 |
| R D R D | 2 + -3 + 5 + -2 + 6 | 8 |
| R R D D | 2 + -3 + 4 + -2 + 6 | 7 |
The best total is 17. Each route is a different mix of two downs and two rights, so a 3 by 3 map has C(4, 2) = 6 routes.
The first attempt is correct. Walk every route, add up the scores, and keep the highest total.
def best_route(grid):
rows, cols = len(grid), len(grid[0])
best = None
stack = [(0, 0, grid[0][0])]
while stack:
r, c, total = stack.pop()
if r == rows - 1 and c == cols - 1:
if best is None or total > best:
best = total
continue
if r + 1 < rows:
stack.append((r + 1, c, total + grid[r + 1][c]))
if c + 1 < cols:
stack.append((r, c + 1, total + grid[r][c + 1]))
return bestNow check the real size. A grid of n by n cells has C(2n - 2, n - 1) routes.
| Grid | Routes |
|---|---|
| 3 by 3 | 6 |
| 10 by 10 | 48,620 |
| 20 by 20 | 35,345,263,800 |
| 30 by 30 | 30,067,266,499,541,040 |
At ten million routes a second, a 30 by 30 grid would take more than 95 years. A real map can have hundreds of rows. Yet only 900 different cells exist in the 30 by 30 grid.
Look at what the first attempt repeats. Many routes pass through the same cell, and each one adds up the cells before it again. The best total to reach a cell does not depend on which route you used to get there.
A spreadsheet works out each cell once, in an order where the cells it uses are ready. A table in code does the same.
In a spreadsheet, you can type a formula in each cell that adds the cell above to the cell on the left. The sheet works out each cell once, in an order where the cells it uses are ready, and shows the number.
No cell is calculated twice. Change one number at the top and the cells below it recalculate. You never write out every route that leads to a cell.
A dynamic programming table is that sheet. Each cell holds the answer to its own question, and its formula reads a few cells that were filled before it. The cells a formula reads are its neighbourhood, and the neighbourhood decides how you fill the sheet.
Predict what happens
Q In the 3 by 3 map, the best total to reach the middle cell is 8 and the best total to reach the cell below it is 11. Do you need to know which routes gave those totals to extend them to the last cell?
Answer: B
The best total to a cell depends only on the best totals of the cells it can come from. The routes themselves are not needed. That is why one number for each cell is enough.
Every grid problem fills a table with one cell for each grid cell. What changes from problem to problem is the set of cells a cell reads. Four neighbourhoods cover the warm-up problems and the lab.
| What a cell reads | Problem | Fill order | Rows to keep |
|---|---|---|---|
| Above and left | Routes, the cheapest path | Row by row, left to right | One row |
| Three cells above | The smallest falling path | Row by row | Two rows |
| Two cells below | The triangle of costs | From the last layer upwards | One list |
| Above, left and diagonal | The largest square, the lab | Row by row, left to right | One row and one variable |
The same three questions settle each one. What does a cell hold? Which cells does it read? In what order are those cells ready?
Take the map [[2, -3, 4], [1, 5, -2], [-1, 3, 6]]. Let best[r][c] be the highest total score of any route from the top left cell to cell (r, c). A route arrives from above or from the left, so a cell takes the higher of the two and adds its own score.
The first row can only come from the left, and the first column only from above. A cell that does not exist is skipped, never read as 0.
| Row | Column 0 | Column 1 | Column 2 |
|---|---|---|---|
| 0 | 2 (start) | -1 (left 2 + -3) | 3 (left -1 + 4) |
| 1 | 3 (above 2 + 1) | 8 (higher of above -1, left 3 + 5) | 6 (higher of above 3, left 8 + -2) |
| 2 | 2 (above 3 + -1) | 11 (higher of above 8, left 2 + 3) | 17 (higher of above 6, left 11 + 6) |
The last cell holds 17, the same answer as the list of routes. The table has 9 cells and each reads at most 2.
Exercise · Predict the output: What is in the last row of the table?. The table fills a treasure map row by row, each cell adding its score to the higher of the cells above and to the left. The program prints the last row. What does it print?
grid = [[3, -1, 2], [-4, 6, -2], [1, -3, 5]]
rows, cols = len(grid), len(grid[0])
best = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
ahead = 0 if r == 0 and c == 0 else -1000000000
if r > 0:
ahead = max(ahead, best[r - 1][c])
if c > 0:
ahead = max(ahead, best[r][c - 1])
best[r][c] = grid[r][c] + ahead
print(*best[rows - 1])Row by row, each cell takes the higher of the cell above and the cell on its left, and adds its own score.
Step by step: Routes on an open grid, row by row. The animated player loads in your browser.
A cell reads the cell above and the cell on its left. So both must be filled first. Row by row, left to right, gives that order. When you reach a cell, the row above is done, and so is the part of its own row to its left.
Another order can break it. Fill the last row first, and a cell reads cells that are still empty, which hold the starting 0. Every number after it is built on a wrong one. The table is only as correct as its order.
Look at what the table reads. A cell reads only the row above and its own row. So you can keep one row of numbers, and overwrite it from left to right.
Before a cell is overwritten, it still holds the value from the row above. The cell on its left has already been overwritten with its new value. So one row holds both cells the new cell needs. For [[2, -3, 4], [1, 5, -2], [-1, 3, 6]] the memory falls from 9 cells to 3.
Exercise · Put it in order: One row for a grid. Arrange the lines into a function that returns the highest total score from the top left cell to the bottom right cell, moving right or down, using one row of numbers.
def best_score(grid):
cols = len(grid[0])
best = [0] * cols
best[0] = grid[0][0]
for c in range(1, cols):
best[c] = best[c - 1] + grid[0][c]
for r in range(1, len(grid)):
best[0] += grid[r][0]
for c in range(1, cols):
best[c] = grid[r][c] + max(best[c], best[c - 1])
return best[cols - 1]
best[0] = grid[r][0]
for c in range(cols):One row is enough when a cell reads only the cell above and the cell on its left.
Step by step: Routes with a closed block. The animated player loads in your browser.
Pick a problem and step through it forwards and back. The cells a new cell reads from are highlighted and joined to it. The routes tables read above and left. In the common letters table, a match reads the diagonal cell, and a mismatch reads above and left.
Try these three, in order:
The visualizer: pick a grid or a map, then step through the algorithm on it. It loads in your browser.
Predict what happens
Q A table is filled from the last row to the first, but each cell reads the cell above and the cell on its left. What goes wrong?
Answer: B
A cell can use a neighbour only after that neighbour is filled and correct. Filling from the end reads cells that still hold the starting 0, and the error spreads to every cell after it.
Every grid solution has the three parts from the first lesson, now with a cell for each square.
best[r][c] is the highest total score of any route from the top left cell to cell (r, c), counting both ends.A cell is filled only after every cell it reads is filled, so each cell holds the best value for its own question, built from correct neighbours.
Why is the table right? The start cell is right by definition. Each other cell is the best of the ways to arrive, and each way ends at a neighbour whose best total is already right. Taking the best neighbour is the best way, so the cell is right too, and so on up to the last cell.
Here is the 2-D table as code. Read the markers beside the explanation above, then see the same table with one row.
def best_score(grid):
rows = len(grid)
cols = len(grid[0])
# [1] best[r][c] is the highest total score of any route from the top left cell to cell (r, c), counting both ends.
best = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
# [2] The start has nothing before it. Any other cell takes the higher of the cells it can come from, above and to the left. A cell outside the grid is skipped.
ahead = 0 if r == 0 and c == 0 else -1000000000
if r > 0:
ahead = max(ahead, best[r - 1][c])
if c > 0:
ahead = max(ahead, best[r][c - 1])
best[r][c] = grid[r][c] + ahead
# [3] The last cell holds the answer. Every cell it reads was filled earlier, because the loops go row by row, left to right.
return best[rows - 1][cols - 1]public int bestScore(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
// [1] best[r][c] is the highest total score of any route from the top left cell to cell (r, c), counting both ends.
int[][] best = new int[rows][cols];
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
// [2] The start has nothing before it. Any other cell takes the higher of the cells it can come from, above and to the left. A cell outside the grid is skipped.
int ahead = (r == 0 && c == 0) ? 0 : -1000000000;
if (r > 0) {
ahead = Math.max(ahead, best[r - 1][c]);
}
if (c > 0) {
ahead = Math.max(ahead, best[r][c - 1]);
}
best[r][c] = grid[r][c] + ahead;
}
}
// [3] The last cell holds the answer. Every cell it reads was filled earlier, because the loops go row by row, left to right.
return best[rows - 1][cols - 1];
}int bestScore(vector<vector<int>> grid) {
int rows = grid.size();
int cols = grid[0].size();
// [1] best[r][c] is the highest total score of any route from the top left cell to cell (r, c), counting both ends.
vector<vector<int>> best(rows, vector<int>(cols, 0));
for (int r = 0; r < rows; r++) {
for (int c = 0; c < cols; c++) {
// [2] The start has nothing before it. Any other cell takes the higher of the cells it can come from, above and to the left. A cell outside the grid is skipped.
int ahead = (r == 0 && c == 0) ? 0 : -1000000000;
if (r > 0) {
ahead = max(ahead, best[r - 1][c]);
}
if (c > 0) {
ahead = max(ahead, best[r][c - 1]);
}
best[r][c] = grid[r][c] + ahead;
}
}
// [3] The last cell holds the answer. Every cell it reads was filled earlier, because the loops go row by row, left to right.
return best[rows - 1][cols - 1];
}function bestScore(grid) {
const rows = grid.length;
const cols = grid[0].length;
// [1] best[r][c] is the highest total score of any route from the top left cell to cell (r, c), counting both ends.
const best = Array.from({ length: rows }, () => new Array(cols).fill(0));
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
// [2] The start has nothing before it. Any other cell takes the higher of the cells it can come from, above and to the left. A cell outside the grid is skipped.
let ahead = r === 0 && c === 0 ? 0 : -1000000000;
if (r > 0) {
ahead = Math.max(ahead, best[r - 1][c]);
}
if (c > 0) {
ahead = Math.max(ahead, best[r][c - 1]);
}
best[r][c] = grid[r][c] + ahead;
}
}
// [3] The last cell holds the answer. Every cell it reads was filled earlier, because the loops go row by row, left to right.
return best[rows - 1][cols - 1];
}def best_score(grid):
rows = len(grid)
cols = len(grid[0])
# [1] best[c] is the highest total for column c of the row being filled. The first row can only come from the left, so each cell adds to the one before it.
best = [0] * cols
best[0] = grid[0][0]
for c in range(1, cols):
best[c] = best[c - 1] + grid[0][c]
for r in range(1, rows):
# [2] Column 0 can only come from above, and best[0] still holds the cell above.
best[0] += grid[r][0]
for c in range(1, cols):
# [3] Any other cell takes the higher of above, which best[c] still holds, and left, which best[c - 1] already holds as its new value.
best[c] = grid[r][c] + max(best[c], best[c - 1])
# [4] The last cell of the last row holds the answer.
return best[cols - 1]public int bestScore(int[][] grid) {
int rows = grid.length;
int cols = grid[0].length;
// [1] best[c] is the highest total for column c of the row being filled. The first row can only come from the left, so each cell adds to the one before it.
int[] best = new int[cols];
best[0] = grid[0][0];
for (int c = 1; c < cols; c++) {
best[c] = best[c - 1] + grid[0][c];
}
for (int r = 1; r < rows; r++) {
// [2] Column 0 can only come from above, and best[0] still holds the cell above.
best[0] += grid[r][0];
for (int c = 1; c < cols; c++) {
// [3] Any other cell takes the higher of above, which best[c] still holds, and left, which best[c - 1] already holds as its new value.
best[c] = grid[r][c] + Math.max(best[c], best[c - 1]);
}
}
// [4] The last cell of the last row holds the answer.
return best[cols - 1];
}int bestScore(vector<vector<int>> grid) {
int rows = grid.size();
int cols = grid[0].size();
// [1] best[c] is the highest total for column c of the row being filled. The first row can only come from the left, so each cell adds to the one before it.
vector<int> best(cols, 0);
best[0] = grid[0][0];
for (int c = 1; c < cols; c++) {
best[c] = best[c - 1] + grid[0][c];
}
for (int r = 1; r < rows; r++) {
// [2] Column 0 can only come from above, and best[0] still holds the cell above.
best[0] += grid[r][0];
for (int c = 1; c < cols; c++) {
// [3] Any other cell takes the higher of above, which best[c] still holds, and left, which best[c - 1] already holds as its new value.
best[c] = grid[r][c] + max(best[c], best[c - 1]);
}
}
// [4] The last cell of the last row holds the answer.
return best[cols - 1];
}function bestScore(grid) {
const rows = grid.length;
const cols = grid[0].length;
// [1] best[c] is the highest total for column c of the row being filled. The first row can only come from the left, so each cell adds to the one before it.
const best = new Array(cols).fill(0);
best[0] = grid[0][0];
for (let c = 1; c < cols; c++) {
best[c] = best[c - 1] + grid[0][c];
}
for (let r = 1; r < rows; r++) {
// [2] Column 0 can only come from above, and best[0] still holds the cell above.
best[0] += grid[r][0];
for (let c = 1; c < cols; c++) {
// [3] Any other cell takes the higher of above, which best[c] still holds, and left, which best[c - 1] already holds as its new value.
best[c] = grid[r][c] + Math.max(best[c], best[c - 1]);
}
}
// [4] The last cell of the last row holds the answer.
return best[cols - 1];
}A cell on the first row has no cell above it. Reading it as 0 is a mistake whenever a real total can be lower than 0, or when the table takes a minimum and 0 looks cheap.
For [[-1, 0], [0, 0]] a table that reads a missing neighbour as 0 returns 0, and the best route earns -1. Skip a cell that does not exist, and start the comparison from a very low number. For a minimum, start from a very high one.
Exercise · Break it: Find the map where a missing cell looks like treasure. This table reads a cell that is outside the grid as 0. Find a map, with at least one row and column, where its best total is higher than the real best total.
def best_score(grid):
rows, cols = len(grid), len(grid[0])
best = [[0] * cols for _ in range(rows)]
for r in range(rows):
for c in range(cols):
up = best[r - 1][c] if r > 0 else 0
left = best[r][c - 1] if c > 0 else 0
best[r][c] = grid[r][c] + max(up, left)
return best[rows - 1][cols - 1]Now allow a third move, one cell diagonally down and to the right. A cell reads three cells: above, left, and diagonally up and to the left. Two of them are easy. The diagonal cell is the trouble when you keep one row.
In one row, the diagonal cell is the old value of the cell on the left. That cell has been overwritten before you need it. So save each cell's old value in a variable before you overwrite it, and use it for the next column.
With one row, the diagonal cell is the old value of the cell on the left, so save each old value before the overwrite.
For the grid [[1, -9], [-9, 1]], the diagonal route scores 2 and a route that only goes right and down scores -7. A one-row table that forgets the saved diagonal reads the new left value twice, and for [[0, -1], [-2, 1]] it returns 0 where the answer is 1. This is the same trick the largest square problem uses.
Sometimes a cell cannot be worked out from the cells before it, because the answer depends on what is still ahead. Take a health that must never drop below 1. The health needed on entering a room depends on the rooms after it. So the table starts at the exit and reads the cells below and to the right.
A triangle of layers is the same. When the last layer is known and the first is not, start at the last layer and read the two cells below. Each cell then finds its inputs ready, and there are no edge cases to handle.
Exercise · Find the bug: The triangle that stops one row early. This code finds the smallest total on a path from the top of a triangle to the bottom, moving to one of the two cells below. It works from the last row upwards, and gives a wrong total on some triangles. Which line is wrong?
def smallest_total(triangle):
row = triangle[-1][:]
for r in range(len(triangle) - 2, 0, -1):
for c in range(r + 1):
row[c] = triangle[r][c] + min(row[c], row[c + 1])
return row[0]Predict what happens
Q A one-row table fills each row from left to right. A cell now also reads the diagonal cell, up and to the left. Why does the plain overwrite fail?
Answer: B
The cell on the left already holds its new value. The diagonal cell is its old value from the row above. Save the old value in a variable before the overwrite, and use it for the next column.
Predict what happens
Q A cell reads above, left and the diagonal. In a 2 by 2 grid, which cells does the bottom right cell read?
Answer: B
The bottom right cell can come from above, from the left, or diagonally from the top left cell. It does not read itself, and the other cells it reads exist in the grid.
Now write it yourself. The lab has one function, best_score_diagonal(grid). It returns the highest total score of a route from the top left cell to the bottom right cell. A move goes right, down or diagonally down and to the right.
Here is a small run on [[1, -9], [-9, 1]]. Both off-diagonal cells are hazards.
| Row | Column 0 | Column 1 |
|---|---|---|
| 0 | 1 (start) | -8 (left 1 + -9) |
| 1 | -8 (above 1 + -9) | 2 (highest of above -8, left -8, diagonal 1, plus 1) |
The answer is 2: the diagonal skips both hazards. Without the diagonal move it would be -7.
Three rules keep it correct:
Build it yourself: write the code in Python, JavaScript, Java or C++ and run the tests. It loads in your browser.
The cost of a grid table is the number of cells times the cells read for each.
| Question | Above and left | With the diagonal as well |
|---|---|---|
| Time | O(R × C): 2 reads for each cell | O(R × C): 3 reads for each cell |
| Memory | O(C) with one row, or O(R × C) for the whole table | O(C) with one row and one saved variable |
| Steps for 500 by 500 | About 500,000 reads | About 750,000 reads |
| What to keep | One row | One row and the saved diagonal |
Keep the whole table when you must recover the route itself, by walking back from the last cell. Keep one row when only the number matters.
Use a grid table when the moves go in fixed directions, such as right and down. A cell's best value must depend on the cells it can come from. Words such as "moves only right or down", "the number of routes", "the cheapest path" and "the largest square" are the hint.
Write the state as one sentence first. Then list the cells it reads, and the order and the memory follow.
Do not use a one-pass grid table when moves can go in every direction, such as up, down, left and right with different costs. A cell then depends on cells that depend on it, and no fill order exists. Use a shortest-path method such as Dijkstra's.
Do not use it when you must list every route rather than count or optimise. Use backtracking.
A one-row table with diagonal moves that writes best[c] = grid[r][c] + max(best[c], best[c - 1]) ignores the diagonal. Writing max(best[c], best[c - 1], best[c - 1]) reads the overwritten left value twice. For grid = [[0, -1], [-2, 1]] it returns 0, and the answer is 1. Save the old value of each cell before you overwrite it.
A one-row table that reads the overwritten left cell twice returns the wrong score.
A one-row table that fills the first row and then loops for c in range(1, cols) in every row never updates best[0]. Column 0 keeps the first row's value. For grid = [[2, 0], [1, 0]] it returns 2, and the answer is 3. Add best[0] += grid[r][0] at the start of each row.
up = best[r - 1][c] if r else 0 looks harmless, but with scores below 0 it makes a missing cell look better than a real one. For grid = [[-1, 0], [0, 0]] it returns 0, and the answer is -1. Skip a cell that does not exist, and start from a very low number.
ahead = 0 for every cell is the same mistake as a missing neighbour read as 0. Only the start cell begins at 0. Every other cell starts from a very low number and takes the best of the cells it can come from.
Explain the three questions in your own words, then take the checkpoint quiz. The checkpoint counts when you pass both the quiz and the lab.
Explain it back: write the idea in your own words and get feedback.
Checkpoint · What a cell reads
Q1/2 A grid cell reads the cell above and the cell on its left. Which fill order works?
Answer: A
Both cells it reads must be filled first. Row by row, left to right, means the row above is done and so is the part of its own row to its left. A cell is not independent: it reads two others.
Q2/2 A table keeps one row and overwrites it from left to right. A cell reads the cell above and the cell on its left. Why is one row enough?
Answer: B
The overwrite goes from left to right. The cell to be overwritten still holds the old value from the row above, and the cell on its left already holds its new value. That is exactly what a cell reads.
Checkpoint · The first lines
Q1/2 For grid = [[-1, 0], [0, 0]], the best route (right and down) earns -1. What does a table that reads a missing neighbour as 0 return?
Answer: A
On the first row the cell above does not exist. Reading it as 0 makes it look better than a real total that is below 0, so the table returns 0. Skip a neighbour that does not exist, and start from a very low number.
Q2/2 In a table that takes a minimum, what should a neighbour outside the grid look like?
Answer: B
A missing neighbour must never be chosen. For a minimum that means a number higher than any real total. For a maximum it means a very low number. Skipping the neighbour is the safest way.
Checkpoint · The diagonal
Q1/2 A one-row table now needs the diagonal cell, up and to the left. What must the code do?
Answer: B
The diagonal cell was the old value of the cell on the left. That cell has already been overwritten. Save each cell's old value in a variable before the overwrite, and use it for the next column.
Q2/2 For grid = [[1, -9], [-9, 1]] with moves right, down and diagonal, what is the highest total score?
Answer: A
The diagonal move goes straight from the start cell to the last cell, so the route visits two cells with scores 1 and 1. The total is 2. A route that only goes right and down must cross a hazard of -9 and scores -7.
Checkpoint · Backwards
Q1/2 When should a grid table be filled from the end to the start?
Answer: B
A cell filled from the start cannot know what lies ahead. If the value needed in a cell depends on later cells, such as the health needed to survive to the exit, start at the end and read the cells below and to the right.
Q2/2 A triangle of costs has a known last layer. Which direction removes the special cases at the edges?
Answer: B
From the last layer up, every cell reads two cells in the layer below, and both always exist. From the top down, the cells at the edges have only one cell above them.
Checkpoint · Memory
Q1/2 A cell reads the three cells above it: straight up, up-left and up-right. How many rows of memory do you keep?
Answer: B
Filling one row in place from left to right overwrites the up-left cell before the next column needs it. Keep the row above in one list and build the new row in another.
Q2/2 A grid has 500 rows and 500 columns, and each cell reads 2 cells. About how many reads does the table make?
Answer: A
The cost is cells times reads for each: 250,000 cells with 2 reads is 500,000 reads. The number of routes is far larger, and the table never lists them.
Review cards from this lesson.
Step through the idea on your own input, then build it in the lab. Runs in your browser. Visualiser and lab.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.