We need to answer: "You are given a grid of m x n rooms. Some rooms are blocked. You start at the top-left and want to reach the bottom-right. You can only move right or down. Write a function to find the number of unique paths. Please this is a classic dynamic programming problem, write a function that solves this problem, explain your DP state and recurrence relation, and how do you handle the blocked rooms."
So we need to produce a solution: explanation and code. The problem is "Unique Paths with Obstacles" (LeetCode 63). Starting from (0,0) to (m-1,n-1) moving only right or down, obstacles are given as grid with 1 for obstacle, 0 for free. We need number of paths. Classic DP: dp[i][j] = number of ways to reach cell (i,j). dp[0][0] = 1 if start not blocked else 0. For each cell: if blocked then dp[i][j]=0; else dp[i][j] = (dp[i-1][j] if i>0 else 0) + (dp[i][j-1] if j>0 else 0). Use modulo? Typically large numbers maybe but not mentioned. So we just return integer. Also handle edge cases: if start or end blocked => return 0.
We can write code in Python. Or any language. We'll explain DP state: dp[i][j] = number of unique paths from start to (i,j) without obstacles. Recurrence: as above. Space optimization: we can use 1D array because we only need previous row and current row; but we can keep 2D for clarity.
But we should also mention time complexity O(mn), space O(mn) or O(n) with optimization.
We'll produce a function: uniquePathsWithObstacles(obstacleGrid: List[List[int]]) -> int.
Let's craft answer.
But the user says: "You are given a grid of m x n rooms. Some rooms are blocked. You start at the top-left and want to reach the bottom-right. You can only move right or down. Write a function to find the number of unique paths. Please this is a classic dynamic programming problem, write a function that solves this problem, explain your DP state and recurrence relation, and how do you handle the blocked rooms."
So we need to output: function + explanation. Possibly also discuss handling of blocked cells: treat them as 0 paths and not allow moves into them.
Let's produce thorough answer.
We'll do:
- Explanation of DP state.
- Recurrence relation.
- Base cases.
- Handling blocked rooms.
- Implementation details (space optimization).
- Complexity.
- Code.
We can provide Python code.
Let's produce final answer.
Solution Overview
We are given an m × n grid where each cell is either free (0) or blocked (1). Starting at the top‑left cell (0,0) we may move only right or down.
We need the number of distinct paths that reach the bottom‑right cell (m‑1,n‑1) while never stepping on a blocked cell.
This is a classic dynamic programming problem often called “Unique Paths with Obstacles.”
DP State
Let dp[i][j] denote the number of ways to reach cell (i, j) from the start, respecting the movement constraints and avoiding obstacles.
i ranges from 0 to m-1, j from 0 to n-1.
- The grid itself is given as
obstacleGrid, where obstacleGrid[i][j] == 1 means the cell is blocked.
Recurrence Relation
For a free cell (obstacleGrid[i][j] == 0), the number of ways to arrive is the sum of ways from the cell above and the cell to the left (the only two possible predecessors):
dp[i][j] = dp[i-1][j] + dp[i][j-1]
If the cell is blocked, we cannot step on it, so:
dp[i][j] = 0
Base Cases
These base cases are naturally covered by the general recurrence if we treat out‑of‑bounds indices as 0.
Handling Blocked Rooms
A blocked cell is assigned dp = 0. Because the recurrence uses only values from neighboring cells, any path that would go through a blocked cell automatically contributes 0 to downstream cells. The start or end being blocked is handled by the base case: the algorithm returns 0 if either is blocked.
Space Optimization (Optional)
Notice that each dp[i][j] depends only on the current row and the previous row. We can compress the 2‑D table into a 1‑D array dp[j] representing the current row. While iterating row by row:
if obstacleGrid[i][j] == 1:
dp[j] = 0
else:
dp[j] = dp[j] (value from the previous row, i-1) + dp[j-1] (value from left in current row)
dp[0] is initialized based on the start cell and then updated for each row.
Space complexity becomes O(n) instead of O(mn).
Complexity Analysis
- Time:
O(m·n) – we visit each cell exactly once.
- Space:
O(n) with 1‑D DP (or O(mn) with the straightforward 2‑D version).
Reference Implementation (Python)
def uniquePathsWithObstacles(obstacleGrid):
"""
Returns the number of unique paths from top-left to bottom-right
in a grid with obstacles, moving only right or down.
Parameters
----------
obstacleGrid : List[List[int]]
0 = free cell, 1 = blocked cell
Returns
-------
int
Number of unique obstacle‑free paths.
"""
if not obstacleGrid or not obstacleGrid[0]:
return 0
m, n = len(obstacleGrid), len(obstacleGrid[0])
# If start or end is blocked, immediate 0
if obstacleGrid[0][0] == 1 or obstacleGrid[m-1][n-1] == 1:
return 0
# dp[j] will hold the number of ways to reach column j in the current row
dp = [0] * n
# Initialize first cell
dp[0] = 1
for i in range(m):
for j in range(n):
if obstacleGrid[i][j] == 1:
dp[j] = 0
else:
if j > 0:
dp[j] += dp[j-1]
# If j == 0, dp[j] stays as the value from the previous row (i-1,0)
# (which is already in dp[j] before the inner loop iteration)
return dp[-1]
Explanation of the Code
- Input validation – handle empty grid.
- Early exit – if start or finish is blocked, answer is
0.
- Initialize a 1‑D DP array of length
n. dp[0] = 1 because there is exactly one way to be at the start if it’s free.
- Iterate over rows (
i):
- For each row, iterate over columns (
j).
- If the current cell is blocked, set
dp[j] = 0 (no paths can end here).
- Otherwise, if
j > 0, add dp[j-1] (paths from the left) to dp[j] (which already contains paths from above from the previous row). For j == 0 we simply keep the value from above (the only possible predecessor).
- After processing the last row,
dp[n-1] holds the number of paths to the bottom‑right corner.
The function works for all valid inputs and runs in O(mn) time with O(n) extra space.
Quick Test
grid = [
[0,0,0],
[0,1,0],
[0,0,0]
]
print(uniquePathsWithObstacles(grid)) # Output: 2
The two valid paths are: right → right → down → down and down → down → right → right (avoiding the obstacle at (1,1)).