To solve this problem, we need to count the number of unique paths from the top-left corner to the bottom-right corner of a grid, avoiding blocked cells. The allowed movements are right and down.
Approach
- Dynamic Programming (DP) Setup: We use a DP table
dpwheredp[i][j]represents the number of ways to reach cell(i, j)from the top-left corner(0, 0). - Base Cases:
dp[0][0] = 1if the starting cell is not blocked.- For the first row, each cell can only be reached from the left cell (if not blocked).
- For the first column, each cell can only be reached from the cell above (if not blocked).
- DP Transition: For any cell
(i, j)(not blocked), the number of paths to it is the sum of paths from the cell above(i-1, j)and the cell to the left(i, j-1). - Edge Handling: If the start or end cell is blocked, the result is 0.
Solution Code
m, n = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(m)]
# Check if start or end is blocked
if grid[0][0] == 1 or grid[-1][-1] == 1:
print(0)
else:
dp = [[0] * n for _ in range(m)]
dp[0][0] = 1
# Fill first row
for j in range(1, n):
if grid[0][j] == 0:
dp[0][j] = dp[0][j-1]
# Fill first column
for i in range(1, m):
if grid[i][0] == 0:
dp[i][0] = dp[i-1][0]
# Fill the rest of the grid
for i in range(1, m):
for j in range(1, n):
if grid[i][j] == 0:
dp[i][j] = dp[i-1][j] + dp[i][j-1]
print(dp[-1][-1])
Explanation
- Dynamic Programming Table: The DP table efficiently stores the number of paths to each cell, avoiding redundant calculations.
- Path Calculation: By summing paths from the top and left cells, we ensure we only consider valid movements (right and down) and avoid blocked cells.
- Efficiency: The algorithm runs in O(m*n) time complexity, where m is the number of rows and n the number of columns, making it suitable for typical grid sizes.
This approach correctly computes the number of valid paths by leveraging dynamic programming to build up the solution from smaller subproblems. It handles edge cases like blocked start/end cells and ensures all paths are valid.

作者声明:本文包含人工智能生成内容。