Problem Description
Given an m x n grid where some cells contain obstacles (represented by 1) and others are free (represented by 0), a robot starts at the top-left corner and wants to reach the bottom-right corner by only moving either down or right. The task is to compute the number of unique paths that avoid obstacles.
Key Insights
- Use Dynamic Programming (DP) to build up the solution by calculating the number of paths to reach each cell.
- For any cell, if it is not an obstacle, the number of paths to reach it equals the sum of the paths from the cell directly above and the cell to the left.
- Cells containing obstacles are set to 0, meaning no path can go through them.
- Special handling is required for the first row and first column since the robot can only come from one direction for those cells.
- If the starting cell has an obstacle, the answer is immediately 0.
Space and Time Complexity
Time Complexity: O(m * n) - Each cell is processed once.
Space Complexity: O(m * n) - Using an auxiliary grid for DP. An optimization to O(n) space is possible by reusing a single row.
Solution
We use a 2D dynamic programming approach where a dp array is maintained with the same dimensions as the grid. Initially, dp[0][0] is set to 1 if the starting cell is free, otherwise 0. The first row and first column are filled based on the absence of obstacles until a blockage is met. Then, for every other cell, if it is free, the value in dp[i][j] is computed as the sum of dp[i-1][j] (from above) and dp[i][j-1] (from left). If the cell is an obstacle, the value is 0. This continues until the bottom-right cell is computed.