Graphs · Exercise 54 of 100

Counting paths across a grid

When you may move only right or down, each path into a cell comes from directly above or directly to its left. Give an open starting cell a count of one and blocked cells a count of zero. Fill the other open cells row by row by adding the counts of those two neighbors, treating positions outside the grid as zero.

Try it yourself

A grid has 3 rows and 4 columns, numbered from 1 at the top left. Only the cell in row 2, column 2 is blocked. How many paths go from the top left to the bottom right using only right and down moves?

One-step hint

Seed the start with one and the blocked cell with zero. For every other cell, add the counts of its existing neighbors above and to the left.

Worked solution
  1. The top row has counts 1, 1, 1, 1. In the second row the blocked cell contributes zero, giving counts 1, 0, 1, 2.
  2. The bottom row starts with 1, then reaches 1 and 2 in the next cells. The final cell gets 2 paths from above and 2 from the left, giving 4.
DSA compiler