91. Paths around the walls
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
Input
grid = [[0, 0, 0],
[0, 1, 0],
[0, 0, 0]]Output
2ExplanationRound the wall by the top or by the left.
Example 2
Input
grid = [[0, 1],
[0, 0]]Output
1ExplanationDown, then right.
Example 3
Input
grid = [[1]]Output
0ExplanationThe start is a wall.
Constraints
gridhas 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.
- Every route into a cell arrives from the cell above it or from the cell to its left. So the routes to a cell are the routes to the cell above plus the routes to the cell on the left.
- Fill a table of counts the same size as the grid, row by row: the start gets 1 (if it's open), a wall gets 0, and a cell on the top row or left column has only one neighbour to add.
- The bottom-right count is the answer. Each cell is worked out once, so even 12 by 12 takes only 144 steps.
Solve it without hints for 3 stars, with hints for 2, after seeing the solution for 1.
One way to solve it, once you've had a go.
Solving it after seeing the solution earns 1 star.
Was this challenge helpful?
Thanks!
Your Submits show here, with their code, so you can go back to one. They stay in this browser.
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
Run your code to see how it does on the test cases, or Submit to check every test.