Unique Paths II - Problem
Imagine a robot starting at the top-left corner of an m ร n grid, trying to reach the bottom-right corner. The robot can only move right or down at each step - no diagonal moves allowed!
Here's the twist: some cells in the grid contain obstacles (marked as 1) that block the robot's path, while empty spaces are marked as 0. The robot must navigate around these obstacles.
Your mission: Calculate how many different unique paths the robot can take to reach its destination while avoiding all obstacles.
Example: In a 3ร3 grid with an obstacle in the middle, the robot might have multiple ways to reach the goal by going around the obstacle.
Input & Output
example_1.py โ Basic Grid with Obstacle
$
Input:
obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]]
โบ
Output:
2
๐ก Note:
There are 2 ways to reach the bottom-right corner: 1) Right โ Right โ Down โ Down, 2) Down โ Down โ Right โ Right. The path Right โ Down โ Right โ Down is blocked by the obstacle.
example_2.py โ Single Cell with Obstacle
$
Input:
obstacleGrid = [[0,1],[0,0]]
โบ
Output:
1
๐ก Note:
Only one path exists: Down โ Right. The path Right โ Down is blocked by the obstacle in the top-right corner.
example_3.py โ Starting Position Blocked
$
Input:
obstacleGrid = [[1]]
โบ
Output:
0
๐ก Note:
The robot cannot move because the starting position itself is blocked by an obstacle.
Constraints
- m == obstacleGrid.length
- n == obstacleGrid[i].length
- 1 โค m, n โค 100
- obstacleGrid[i][j] is 0 or 1
- The testcases are generated so that the answer will be less than or equal to 2 ร 109
Visualization
Tap to expand
Understanding the Visualization
1
Setup
Robot starts at top-left, needs to reach bottom-right
2
Movement Rules
Can only move right (โ) or down (โ), never backward
3
Obstacles
Blocked cells (marked 1) cannot be entered
4
Path Counting
Count all unique valid routes to destination
Key Takeaway
๐ฏ Key Insight: Use dynamic programming to build up the solution - each cell's path count equals the sum of paths from the cell above and the cell to the left, unless blocked by obstacles.
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code