Exercise: the DP principle
Before this unit: Day 27: Graph cuts.
See also: Day 30: Snakes and active shape models; Day 13: Morphology; Day 15: Watershed.
Goal
By the end of this exercise you should be able to:
- fill the DP table of a minimal path by hand, and recover the path by backtracking,
- explain why greedy choices fail and why trying all paths is hopeless,
- count the operations of DP and the number of paths,
- recognise the same recursion in the two-label chain (graph-cut day) and the distance transform (morphology day),
- (math) prove the principle of optimality and count paths and operations in general.
Do the pen-and-paper part first, then the demo. Questions marked (math) are for those who want the derivations; the concept questions do not depend on them.
Background
| Idea | What it means |
|---|---|
| Cost image C | one number per pixel; a path pays the sum of its pixels |
| Monotone path | one pixel per row, from the top row to the bottom row; each step goes one row down and at most one column sideways (↙ ↓ ↘) |
| Table M | M(i, j) = cost of the cheapest path from the top row to pixel (i, j) |
| Recursion | M(0, j) = C(0, j); M(i, j) = C(i, j) + \min\big(M(i-1, j-1), M(i-1, j), M(i-1, j+1)\big) |
| Pointer | which of the cells above gave the minimum |
| Backtracking | start at the smallest M of the last row and follow the pointers up |
| Tie rule (demo) | on a tie, straight wins, then left, then right |
Pixels are written (row, column), counting from 0; row 0 is the top.
By hand
B1. The cost image of the lecture:
| 0 | 1 | 2 | 3 | 4 | |
|---|---|---|---|---|---|
| 0 | 7 | 4 | 8 | 8 | 3 |
| 1 | 2 | 9 | 3 | 8 | 2 |
| 2 | 3 | 1 | 3 | 6 | 8 |
| 3 | 5 | 1 | 7 | 3 | 2 |
| 4 | 9 | 2 | 3 | 9 | 6 |
- Fill the 5 \times 5 table M and draw the pointers.
- Find the cheapest path and its cost by backtracking.
- The greedy path starts at the cheapest pixel of the top row and always steps to the cheapest of the (up to) three pixels below. Which path is that, and what does it cost? Where does it go wrong?
B2. Counting. (a) How many monotone paths does a 5 \times 5 image have? (Count them with the same kind of table: the number of paths that reach each cell.) Compare with m \cdot 3^{n-1}. (b) How many candidate evaluations (one addition and one comparison each) does filling the table of B1 take? (c) For a 100 \times 100 image: roughly how many paths, and how many evaluations? If a computer checks 10^9 paths per second, how long would trying them all take? (The age of the universe is about 4 \cdot 10^{17} s.)
B3. The two-label chain from the graph-cut day: I = (3, 3, 1, 3, 0), \mu_0 = 0, \mu_1 = 3, D_p(\ell) = (I_p - \mu_\ell)^2 and \lambda = 2. (a) Write it as a minimal path: what are the stages, the states, the cost of each “pixel” of the path, and the cost of a step? (b) Fill the table M_k(0), M_k(1) for k = 1, \dots, 5 and backtrack. Compare with the graph-cut day’s exercise.
B4. The forward pass of the distance transform (morphology day) on a 3 \times 4 image whose only background pixel is the top-right one, (0, 3). Start with D = 0 there and D = \infty elsewhere, and visit the pixels in raster order (row by row, left to right) with D(i, j) \leftarrow \min\big(D(i, j), D(i-1, j) + 1, D(i, j-1) + 1\big). (a) Write down D after this one pass. Which pixels are wrong, and why? (b) Which order would a second pass need to fix them?
B5. Predict. In the cost image of B1, change C(0, 4) from 3 to 1. Does the cheapest path change? Does the greedy path? Answer without refilling the whole table: which entries of M change?
B1. (a)
| M | 0 | 1 | 2 | 3 | 4 |
|---|---|---|---|---|---|
| 0 | 7 | 4 | 8 | 8 | 3 |
| 1 | 6 | 13 | 7 | 11 | 5 |
| 2 | 9 | 7 | 10 | 11 | 13 |
| 3 | 12 | 8 | 14 | 13 | 13 |
| 4 | 17 | 10 | 11 | 22 | 19 |
For example M(1, 0) = 2 + \min(7, 4) = 6 (pointer to (0, 1)), M(2, 1) = 1 + \min(6, 13, 7) = 7 (pointer to (1, 0)), M(4, 1) = 2 + \min(12, 8, 14) = 10 (pointer to (3, 1)). (b) The smallest entry of the last row is M(4, 1) = 10. Backtracking: (4, 1) \to (3, 1) \to (2, 1) \to (1, 0) \to (0, 1). The path, top to bottom, has columns 1, 0, 1, 1, 1 and costs 4 + 2 + 1 + 1 + 2 = 10. (c) Greedy: (0, 4) with 3, then (1, 4) with 2, then the cheapest of 6 and 8, (2, 3) with 6, then the cheapest of 7, 3, 2: (3, 4) with 2, then the cheapest of 9 and 6: (4, 4) with 6. Total 19. The cheap start in the top-right corner leads into the expensive right part of rows 2 and 4; once there, the cheap column 1 is out of reach.
B2. (a) Counting paths with the table N(0, j) = 1, N(i, j) = \sum N(\text{cells above}): the rows are (1, 1, 1, 1, 1), (2, 3, 3, 3, 2), (5, 8, 9, 8, 5), (13, 22, 25, 22, 13), (35, 60, 69, 60, 35): 259 paths. m \cdot 3^{n-1} = 5 \cdot 81 = 405 overestimates, because the border cells have only 2 cells above. (b) Rows 1–4 each have 3 interior cells with 3 candidates and 2 border cells with 2: 4 \cdot (9 + 4) = 52 evaluations. (c) About 1.5 \cdot 10^{49} paths, against 99 \cdot 298 = 29\,502 evaluations. At 10^9 paths per second: 1.5 \cdot 10^{40} s, about 4 \cdot 10^{22} times the age of the universe.
B3. (a) Stages = the pixels p = 1, \dots, 5; states = the labels 0 and 1; the “cost of a pixel” of the path is the data cost D_p(\ell); a step that keeps the label costs 0, a step that changes it costs \lambda. It is a minimal path through a grid with 5 rows and 2 columns, with a penalty \lambda on the sideways step. (b) D(0) = 9, 9, 1, 9, 0 and D(1) = 0, 0, 4, 0, 9. M_1 = (9, 0); M_2(0) = 9 + \min(9, 0 + 2) = 11, M_2(1) = 0 + \min(0, 9 + 2) = 0; M_3 = (1 + \min(11, 2),\ 4 + \min(0, 13)) = (3, 4); M_4 = (9 + \min(3, 6),\ 0 + \min(4, 5)) = (12, 4); M_5 = (0 + \min(12, 6),\ 9 + \min(4, 14)) = (6, 13). Minimum energy 6, with L_5 = 0; backtracking: L_5 = 0 came from L_4 = 1 (6 = 0 + 4 + 2), L_4 = 1 from L_3 = 1, L_3 = 1 from L_2 = 1, L_2 = 1 from L_1 = 1: the labelling 11110, the same as the graph-cut day’s B3.
B4. (a) After one pass, column 3 is 0, 1, 2 (correct), but all of columns 0–2 are still \infty: their nearest background pixel lies to the right, and the pass only looks up and left, so the information never reaches them. The true distances (city block) are \begin{bmatrix} 3 & 2 & 1 & 0 \\ 4 & 3 & 2 & 1 \\ 5 & 4 & 3 & 2 \end{bmatrix}. (b) The reverse raster order (bottom to top, right to left), looking down and right: D(i, j) \leftarrow \min\big(D(i, j), D(i+1, j) + 1, D(i, j+1) + 1\big). After it, all values are correct. Each pass is a Bellman recursion with its own fixed order; neither order alone covers paths that go both ways.
B5. Only entries that depend on (0, 4) can change: M(0, 4) becomes 1, and below it only cells whose minimum came through (0, 4). M(1, 4) = 2 + \min(8, 1) = 3 and M(1, 3) = 8 + \min(8, 8, 1) = 9; but row 2 then gives M(2, 4) = 8 + 3 = 11, M(2, 3) = 6 + \min(7, 9, 3) = 9, and the cheapest bottom value stays M(4, 1) = 10 (the right part of rows 2–4 is expensive). The best path does not change. Greedy starts at the same pixel as before and pays 1 + 2 + 6 + 2 + 6 = 17: still worse.
Math questions
B6. (math) Prove the principle of optimality for minimal monotone paths: if j_0, \dots, j_{n-1} is a cheapest path and 0 \le k < n-1, then j_0, \dots, j_k is a cheapest path from the top row to (k, j_k). Use it to prove by induction that the recursion gives M(i, j) = the cost of the cheapest path to (i, j).
B7. (math) (a) Show that the number of evaluations to fill an n \times m table (m \ge 2) is exactly (n-1)(3m-2). Check it for B2. (b) Show that the number of monotone paths P satisfies m \cdot 2^{n-1} \le P \le m \cdot 3^{n-1}.
B8. (math) Paths from the top-left to the bottom-right cell with steps right or down only. (a) Write the recursion for M and the order of filling. (b) Show that there are \binom{n + m - 2}{n - 1} such paths in an n \times m grid, and evaluate it for 5 \times 5.
B9. (math) Allow steps of up to \delta columns sideways with a penalty \alpha |d| for a step of d columns. Write the recursion and its cost in operations. Why does a large \alpha give straighter paths?
B6. Suppose j_0, \dots, j_k is not cheapest: some path j'_0, \dots, j'_k with j'_k = j_k costs less. Then j'_0, \dots, j'_k, j_{k+1}, \dots, j_{n-1} is a valid path (the step from j_k to j_{k+1} is unchanged) and costs less than the original, a contradiction. Induction: M(0, j) = C(0, j) is correct. If M(i-1, \cdot) is correct, a cheapest path to (i, j) passes through some (i-1, j+d), |d| \le 1, and by the principle its first part costs M(i-1, j+d); so the cheapest cost is C(i, j) + \min_d M(i-1, j+d), which is the recursion.
B7. (a) Rows 1, \dots, n-1 each have m - 2 interior cells with 3 candidates and 2 border cells with 2: 3(m-2) + 4 = 3m - 2 per row. For 5 \times 5: 4 \cdot 13 = 52. (b) With N(i, j) the number of paths to (i, j): every cell has at least 2 and at most 3 cells above it (for m \ge 2), so by induction 2^i \le N(i, j) \le 3^i. Summing over the m cells of the last row gives the bounds.
B8. (a) M(0, 0) = C(0, 0), M(i, j) = C(i, j) + \min\big(M(i-1, j), M(i, j-1)\big), with M = \infty outside the grid; fill row by row, left to right (both right-hand cells come earlier in this order). (b) A path makes n - 1 down-steps and m - 1 right-steps in some order: choose which n - 1 of the n + m - 2 steps go down. For 5 \times 5: \binom{8}{4} = 70.
B9. M(i, j) = C(i, j) + \min_{|d| \le \delta} \big(M(i-1, j+d) + \alpha|d|\big): 2\delta + 1 candidates per cell, about (2\delta+1)nm operations. A large \alpha makes every sideways step expensive, so the path changes column only where the costs of the image make it worth it: straighter, smoother paths. (\alpha = 0 and \delta = 1 is the case of B1.)
Explore
The demo shows the cost image C (left; light = cheap) and the table M (right). step fills one cell: the candidates in the row above are outlined in blue, the chosen minimum is shaded green and an arrow points back to it (show pointers keeps all arrows). next stage fills a whole row, fill all the table, backtrack follows the arrows from the best cell of the last row; the last frame adds the greedy path (red “g”). The readout counts cells, operations and paths. Click the upper half of a cost cell to raise it by 1, the lower half to lower it. moves → ↓ switches to paths from the top-left to the bottom-right cell.
E1. Preset by-hand exercise grid. Step through the first two rows and compare every entry and arrow with your table from B1. Then fill all and backtrack. What are the operations and the number of paths at the end?
E2. Preset greedy fails. Before stepping, guess the best path. Then end: what do the optimal and the greedy path cost, and why does greedy fail here?
E3. Preset two equal optima. Which path does the demo report? Find the second path with the same cost. Why does the table report only one of them, and how would you change the backtracking to find both?
E4. Preset a detour. The cheap channel of 1s runs down, right, up, right and down again. What does the best monotone path cost, and where does it go? Find a cheaper path by hand if you are allowed to move up, down, left and right. Why can no row-by-row table find it?
E5. Back to by-hand exercise grid, now with moves → ↓. What does the cheapest path from the top-left to the bottom-right cost, how many paths are there, and how many operations does the table take? Check the path count with B8.
E6. Back to by-hand exercise grid (moves ↙ ↓ ↘). Predict first, then check: raise C(0, 1) from 4 to 9 (five clicks on its upper half). Which path is now the cheapest, and what does it cost? Does the greedy path change?
E1. The table and arrows match B1. At the end: 25 of 25 cells filled, 52 operations, 259 paths; optimal cost 10, greedy 19.
E2. Optimal 9: straight down the right column, 3 + 2 + 1 + 2 + 1. Greedy 20: it starts at the 1 in column 2 (the cheapest first pixel), then takes 2, and is then surrounded by 8s and 9s: 1 + 2 + 8 + 8 + 1. The cheapest first step leads into the most expensive region.
E3. The demo reports (0,2), (1,1), (2,0), (3,1), (4,2): cost 1 + 2 + 3 + 2 + 1 = 9. Its mirror image (0,2), (1,3), (2,4), (3,3), (4,2) also costs 9. At (4, 2) the two candidates M(3, 1) = M(3, 3) = 8 tie, and the pointer stores only one (left wins). To find all optimal paths, store all tied predecessors (a set of pointers per cell) and backtrack along every branch.
E4. The best monotone path costs 24: down the channel in column 1 to row 5 (six 1s), then through two 9s and out at the bottom left: (0,1), \dots, (5,1), (6,0), (7,0). Following the channel costs 19 (nineteen cells of cost 1): down column 1, right along row 5 to column 3, up column 3 to row 2, right along row 2 to column 6, and down column 6 to the bottom. A row-by-row table only allows one cell per row and moves downwards, so it cannot represent a path that goes back up; and even if it could, M of a cell in row 2 would depend on cells in row 5, which are filled later. There is no fixed row order: the live-wire unit solves this with Dijkstra’s algorithm.
E5. Cost 32, along (0,0), (1,0), (2,0), (2,1), (3,1), (3,2), (3,3), (3,4), (4,4); 70 paths, 40 operations (every cell except the first row and column has 2 candidates: 16 \cdot 2 + 8 \cdot 1 = 40). \binom{8}{4} = 70, as in B8.
E6. The old path loses its cheap start (it would now cost 15). The new optimum is 13: columns 0, 0, 1, 1, 1, that is 7 + 2 + 1 + 1 + 2: it starts at the 7 and joins the old path in row 1. Greedy is unchanged (it starts at the 3 in the top-right corner): 19. Only the cells whose cheapest path ran through (0, 1) change in M (most of the table); the right column, whose paths never touch (0, 1), is unchanged.
Code
Write the algorithms of this unit yourself, in Rust. Setup, and how to run and check your code: coding exercises: getting started. Your code goes in dynprog/src/dp_paths/exercise.rs.
The code writes a pixel as (x, y) = (column, row), counting from 0. The pixel (row 1, column 0) of B1 is (0, 1) in the code.
C1. dp_table(cost): the table M and the pointers, row by row. The pointer of a cell is the step d \in \{-1, 0, 1\} to the column above that gave the minimum; on a tie, straight wins, then left, then right (as in the demo):
for every column x: M(x, 0) = C(x, 0)
for y = 1, 2, ..., n − 1:
for every column x:
best = ∞
for d in 0, −1, +1: # this order is the tie rule
if column x + d exists and M(x + d, y − 1) < best:
best = M(x + d, y − 1); pointer(x, y) = d
M(x, y) = C(x, y) + best
The check is your table from B1 (a).
C2. backtrack(m, pointer): the column of the path in every row:
x = the column of the smallest M in the last row
for y = n − 1 down to 0:
path[y] = x
x = x + pointer(x, y)
The checks: B1 (b), path 1, 0, 1, 1, 1 with cost 10, and E6, where raising C(0, 1) to 9 gives 13.
C3. greedy_path(cost): start at the cheapest pixel of the top row and always step to the cheapest of the (up to) three pixels below. The checks: B1 (c), cost 19, and B5, cost 17.
C4. count_paths(width, height): the number of paths to every cell, by the same table with a sum in place of the minimum:
N(x, 0) = 1
N(x, y) = N(x − 1, y − 1) + N(x, y − 1) + N(x + 1, y − 1) # only the cells that exist
The check is B2: 259 paths for 5 \times 5, and about 1.5 \cdot 10^{49} for 100 \times 100.
C5. The distance transform as two Bellman recursions (B4), with D = 0 on the background and \infty elsewhere:
distance_forward: one pass in raster order, D(x, y) \leftarrow \min\big(D(x, y), D(x, y-1) + 1, D(x-1, y) + 1\big);distance_two_passes: then a second pass from the bottom right, backwards, looking down and right.
The check is B4: after one pass, columns 0–2 are still \infty.
Then cargo run -p dynprog -- dp-paths and open the pictures in out/dp-paths/. With the grey value as the cost, dark-path.png shows the darkest path from the top to the bottom of the micrograph (orange) and the greedy path (blue). seam.png does the same with the edge strength as the cost. distance-one-pass.png and distance-two-passes.png show the distance to a letter F (black = 0; ∞ is drawn white).
C6. Before you look: where in the micrograph do you expect the darkest path? Then compare it with the greedy path, in the picture and in the two printed costs. Where does greedy go wrong?
C7. The program prints the number of paths of the 256 \times 256 image and the number of candidate evaluations. Compare the two, and the time DP needed.
C8. In distance-one-pass.png, which pixels are still \infty (white) after one pass, and why those? How many pixels are wrong after one pass (printed)?
The model solution is dynprog/src/dp_paths/solution.rs in the download.
C6. The darkest path runs down the dark cytoplasm on the left of the nucleus and along the left part of the nucleus, then down the dark band of cytoplasm below it. Its 256 grey values add up to 60.74. The greedy path starts at the darkest single pixel of the top row, which lies in the pale region at the top; from there it can only move one column per row. It stays in pale material, runs down along the right edge of the nucleus and then through the pale region below it: 107.33. One dark pixel at the start does not make a dark path. With the edge strength as the cost, the seam avoids edges: DP 4.66, greedy 11.24.
C7. About 1.1 \cdot 10^{124} paths, against 255 \cdot (3 \cdot 256 - 2) = 195\,330 candidate evaluations (B7), which take a few milliseconds.
C8. After one pass, the whole strip to the left of the letter’s stem and every row above the letter are still \infty (6016 pixels): their nearest letter pixel lies to the right or below, and the pass only looks up and left. Another 319 pixels have a finite but too large value: the band just above the middle bar of the F, whose nearest letter pixel lies below it. In all, 6335 of the 16 384 pixels are wrong after one pass; the second pass, in the opposite order, fixes all of them.
Where this leads
The table filled row by row works because a monotone path has a natural order. The next unit turns the table sideways: a closed boundary around a nucleus becomes a path through a polar image, with one radius per angle. After that, the live-wire unit drops the fixed order altogether (Dijkstra’s algorithm), and the fast marching unit makes the path continuous. The same table matches two image rows in scanline stereo (day 53).