DP on a Grid
Grids and DP fit together naturally. When moves only go right or down, every cell can be reached only from the cell above it or the cell to its left. So the answer for a cell depends on just two neighbours, both of which come earlier in reading order.
A table the size of the grid
Make a 2D slice with one entry per cell and fill it row by row, left to right:
grid: table (most berries so far):
3 1 4 3 4 8
2 0 9 5 5 17
1 5 1 6 11 18
Each entry is the cell's own value plus the better of the entry above and the entry to the left. The first row can only come from the left, the first column only from above, and the top-left cell is just its own value. The answer is in the bottom-right corner.
best[r][c] = int(grid[r][c]-'0') + max(best[r-1][c], best[r][c-1])
grid[r][c]-'0' turns the digit character into its number: '7' - '0' is 7.
Counting instead of maximising
To count the different routes, the formula changes from "the better of" to "the sum of": every route into a cell arrives either from above or from the left.
ways[r][c] = ways[r-1][c] + ways[r][c-1]
On a 16 × 16 field there are over 155 million routes. A recursion that walks every route one by one would take ages, while the table needs 256 additions.
Blocked cells
A blocked cell gets 0 routes, and nothing can come from it. For the maximum, mark unreachable cells with -1 as in the previous lesson, and only build on neighbours that are reachable. A cell whose neighbours above and to the left are both blocked becomes unreachable too, and that spreads.
Task
This lesson's input is a berry garden. Every cell is a digit, the number of berries it holds, or #, a bush you can't walk into. You start at the top-left cell and finish at the bottom-right one, moving only right or down. The berries of every cell you walk through count, including the first and the last.
- Complete
mostBerries(grid []string) int: the most berries one walk can pick, or-1when no walk gets through. - Complete
countRoutes(grid []string) int: how many different walks there are.