On an open grid the number of paths from the top left to the bottom right, moving only right or down, is a binomial coefficient. With blocked cells you add up the counts of the two neighbours, as in Pascal's triangle.
What to build
A program that counts the paths through a grid with obstacles.
Requirements
- Read R and C, then R lines of C characters:
.is an open cell and#is blocked. - Count the paths from the top-left cell to the bottom-right cell that move one step right or one step down and never enter a blocked cell.
- Print the number of paths. If the start or the end is blocked, the answer is 0.
Input
The first line has R and C. Then R lines with C characters each.
Output
One whole number.
Constraints
1 ≤ R, C ≤ 12.
Example
Input:
2 2
..
..
Output:
2
Why it works
Every path to a cell arrives from the cell above or the cell to the left, and these two groups of paths are different, so by the sum rule the counts add. On an open grid this reproduces Pascal's triangle, so the answer is C(R + C − 2, R − 1); a blocked cell just contributes 0.
Examples
2 2 .. ..
2
3 3 ... .#. ...
2
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Let ways[r][c] be the number of paths to the cell (r, c). A blocked cell has 0.
Hint 2
For an open cell, ways[r][c] is the ways from above plus the ways from the left; the start has 1 way if it is open.
Hint 3
This is Pascal's rule again: a path arrives from one of two neighbours, so the counts add.
Solution
Show one correct solution (try it yourself first)
r, c = map(int, input().split())
grid = [input() for _ in range(r)]
ways = [[0] * c for _ in range(r)]
for i in range(r):
for j in range(c):
if grid[i][j] == "#":
continue
if i == 0 and j == 0:
ways[i][j] = 1
else:
up = ways[i - 1][j] if i > 0 else 0
left = ways[i][j - 1] if j > 0 else 0
ways[i][j] = up + left
print(ways[r - 1][c - 1])
▶ Open this solution in the compiler, then press Visualize to watch it run step by step