Roadworks on the Grid

Easydynamic programmingAlso known as Unique Paths II

A bike courier works in a part of town where the streets form a neat grid. The depot is at the top-left intersection and today's customer is at the bottom-right one. To never waste time, she only ever rides east (right) or south (down).

This week some intersections are fenced off for roadworks and cannot be ridden through. She likes to vary her ride. How many different routes does she have?

Your task

Write countRoutes(grid). grid[r][c] is 0 for an open intersection and 1 for one closed by roadworks. Return the number of different routes from grid[0][0] to the bottom-right cell that move one cell right or one cell down at a time and never enter a closed cell.

If the depot or the customer's intersection is closed, return 0. A 1 × 1 open grid has exactly 1 route (she is already there).

countRoutes(grid: int[][]) → int

Examples

Example 1
Input
grid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Output
2
Why

With no roadworks a 3 × 3 grid has 6 routes. The closed middle kills every route through it, leaving two: all the way right then down, or all the way down then right.

Example 2
Input
grid = [[0, 0, 0, 0], [0, 0, 1, 0], [1, 0, 0, 0]]
Output
3
Why

Count how many ways reach each corner, row by row. The first row is all 1s. The second row is 1, 2, 0 (closed), 1. The third row is 0 (closed), 2, 2, 3. So 3 routes reach the customer.

Constraints

  • 1 ≤ number of rows, number of columns ≤ 20
  • Every row has the same length.
  • grid[r][c] is 0 or 1.
Start with brute force

Explore every route with recursion: from each cell, try going right and try going down, and count the times you reach the customer.

On an open 20 × 20 grid there are over 35 billion routes, and the recursion visits each one. Most of the work repeats: every route that passes through the same middle cell recounts everything after it.

Hints

0 of 4 shown

Walkthrough and solution

Unlocks when you pass every test. Stuck for a while? Looking is fine too, as long as you then close it and write the code yourself.

Ctrl+Enter runs

Run your code to see results here. Run checks the examples. Submit checks every test, including hidden edge cases.

Write code