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
๐Ÿค– Robot Path Navigation๐Ÿค–๐Ÿ“ฆ๐ŸŽฏPath 1: Right โ†’ Right โ†’ Down โ†’ DownPath 2: Down โ†’ Down โ†’ Right โ†’ Right๐Ÿ“ฆ = Obstacle (blocks path)๐Ÿค– = Start position๐ŸŽฏ = DestinationTotal unique paths: 2
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.
Asked in
Google 45 Amazon 38 Microsoft 32 Meta 28 Apple 22
89.2K Views
High Frequency
~18 min Avg. Time
3.4K Likes
Ln 1, Col 1
Smart Actions
๐Ÿ’ก Explanation
AI Ready
๐Ÿ’ก Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen