Leetcode 63: Unique Paths II

grid47
grid47
Exploring patterns and algorithms
Oct 31, 2024 6 min read

A more intricate, glowing path system with a few obstacles, showing varied routes to the goal.
Solution to LeetCode 63: Unique Paths II Problem

A robot starts at the top-left corner of an m x n grid and needs to reach the bottom-right corner. The grid contains obstacles (marked as 1) and empty cells (marked as 0). The robot can only move down or right and cannot pass through cells with obstacles. Determine the number of unique paths to the destination.
Problem
Approach
Steps
Complexity
Input: An integer 2D array grid where grid[i][j] is either 0 (empty) or 1 (obstacle).
Example: Input: obstacleGrid = [[0,0,1],[0,0,0],[1,0,0]]
Constraints:
• m == obstacleGrid.length
• n == obstacleGrid[i].length
• 1 <= m, n <= 100
• obstacleGrid[i][j] is 0 or 1.
Output: Return the number of unique paths from the top-left to the bottom-right corner while avoiding obstacles.
Example: Output: 3
Constraints:
• The result will always be less than or equal to 2 * 10^9.
Goal: Calculate the total number of unique paths from start to destination while avoiding obstacles using dynamic programming.
Steps:
• Initialize a DP table with dimensions m x n to store the number of ways to reach each cell.
• Set dp[0][0] = 1 if grid[0][0] == 0; otherwise set dp[0][0] = 0.
• For each cell (i, j), if grid[i][j] == 0, calculate dp[i][j] as the sum of paths from the top and left neighbors.
• If grid[i][j] == 1, set dp[i][j] = 0 as it is an obstacle.
• Return dp[m-1][n-1] as the final result.
Goal: The grid size and obstacle placements must adhere to the constraints.
Steps:
• 1 <= m, n <= 100
• obstacleGrid[i][j] is either 0 or 1.
• The result will always be less than or equal to 2 * 10^9.
Assumptions:
• The robot starts at grid[0][0] and ends at grid[m-1][n-1].
• A cell marked with 1 is an obstacle and cannot be part of any path.
• The robot can only move down or right.
Input: Input: obstacleGrid = [[0,0,1],[0,0,0],[1,0,0]]
Explanation: There are three unique paths from the top-left to the bottom-right corner avoiding obstacles.

Input: Input: obstacleGrid = [[0,0,0],[0,1,0],[0,1,0]]
Explanation: There is only one unique path that avoids obstacles.

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus