100 XP

91. Paths around the walls

Advanced dynamic programming grids

A grid is a list of rows; each cell is 0 for open ground or 1 for a wall. You start in the top-left cell and want to reach the bottom-right cell, moving one cell at a time, only right or down, and never into a wall.

Write a function count_paths(grid) that returns how many different routes there are.

  • If the start or the end is a wall, there are no routes: 0.
  • A grid of one open cell has one route, which makes no moves.
  • The count can be large: a 12 by 12 grid with no walls has 705,432 routes. Following them one by one takes at least that many steps, while each cell's count comes easily from its neighbours' counts.

Example 1

Inputgrid = [[0, 0, 0], [0, 1, 0], [0, 0, 0]]
Output2
ExplanationRound the wall by the top or by the left.

Example 2

Inputgrid = [[0, 1], [0, 0]]
Output1
ExplanationDown, then right.

Example 3

Inputgrid = [[1]]
Output0
ExplanationThe start is a wall.

Constraints

  • grid has 1 to 12 rows of 1 to 12 cells each, all rows the same length; every cell is 0 or 1.

Submit also runs 10 more tests you can't see.

Code
def count_paths(grid):
    """Count the routes from top-left to bottom-right.

    grid: list of rows of 0 (open) and 1 (wall)
    Returns: int, how many routes move only right or down
        through open cells
    """
    # Write your code here
    pass