Roadworks on the Grid

Easydynamic programmingAlso known as Unique Paths II

A bike courier rides a grid of streets from the depot at the top-left intersection to a customer at the bottom-right. She only ever rides east (right) or south (down).

This week some intersections are fenced off for roadworks. 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 a closed one. Return the number of routes from grid[0][0] to the bottom-right cell that move one cell right or 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

An open 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 the routes that reach each intersection, row by row. The first row is all 1s. The second row is 1, 2, 0 (closed) and 1. The third row is 0 (closed), 2, 2 and 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

Use recursion: from each cell, try moving right and moving down, and count the paths that arrive at the customer.

An open 20 × 20 grid has over 35 billion routes, and the recursion visits each one. Every route through the same middle cell recounts everything that comes 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