Card 05/ 09

WalkthroughDifficulty: Intermediate3 min

Count the Paths Across a Grid

Each cell's count is the count from above plus the count from the left.

Counting the paths across a grid that moves only right or down is a table with one entry per cell, where each entry is the sum of the entry above and the entry to the left. This walkthrough fills that table for a grid with a blocked cell and reads the count from the bottom-right corner.

A warehouse robot starts in the top-left cell of a floor 3 rows by 5 columns and must reach the bottom-right cell, moving one cell right or one cell down at a time. A pallet blocks the cell in row 1, column 2, counting from 0. The state is paths[r][c], the number of routes from the start to cell (r, c). The last move into a cell came either from above or from the left, and those routes do not overlap, so paths[r][c] = paths[r − 1][c] + paths[r][c − 1]. A blocked cell has 0 routes, and a missing neighbour off the edge counts as 0.

Before the table: how many routes reach the bottom-right cell?
  1. Without the pallet there would be 15, so the blocked cell removes 9 routes.

Filling paths[r][c] for 3 rows by 5 columns, with row 1, column 2 blocked

Row 0

The start cell has one route, standing still. Every other cell in the top row can be reached only from the left, so each copies the 1 before it. The first row and the first column are the base cases.

Routes to each cell after row 0
RowColumn 0Column 1Column 2Column 3Column 4
011111

Row 1

Column 0 can be reached only from above: 1. Column 1 adds above and left, 1 + 1 = 2. The blocked cell, marked X, holds 0 whatever its neighbours say. Column 3, in [ ], gets 1 from above and 0 from the blocked cell to its left. Column 4 adds 1 and 1.

Routes to each cell after row 1
RowColumn 0Column 1Column 2Column 3Column 4
011111
112X[1]2

Row 2

Column 0 is 1 again. Column 1 is 2 + 1 = 3. Column 2 gets 0 from the blocked cell above and 3 from the left. Column 3 is 1 + 3 = 4, and the corner is 2 + 4 = 6.

Routes to each cell after row 2
RowColumn 0Column 1Column 2Column 3Column 4
011111
112X12
213346

The corner holds 6, as a run printed, and the same grid with no pallet gives 15. The table has rows × columns entries and each takes one addition, so the count costs O(rows × columns) time. Each row reads only itself and the row above, so one row of five numbers, updated left to right, is enough space.

A blocked cell does not need a special rule in the recurrence: it is a 0, and every cell beside it adds that 0 in. The same table answers related questions by changing one thing. Allowing a diagonal move adds a third term, and asking for the cheapest route instead of the number of routes replaces the sum with a minimum, as Grid DP Example: The Cheapest Route Through a Toll Grid shows.