Difficulty: Medium Link: April Leetcoding Challenge 2021: Day 28
A robot is located at the top-left corner of a
m x n grid (marked ‘Start’ in the diagram below).
The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked ‘Finish’ in the diagram below).
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and space is marked as
0 respectively in the grid.
Input: obstacleGrid = [[0,0,0],[0,1,0],[0,0,0]] Output: 2 Explanation: There is one obstacle in the middle of the 3x3 grid above. There are two ways to reach the bottom-right corner: 1. Right -> Right -> Down -> Down 2. Down -> Down -> Right -> Right
Input: obstacleGrid = [[0,1],[0,0]] Output: 1
m == obstacleGrid.length
n == obstacleGrid[i].length
1 <= m, n <= 100
A naive approach could be to try and find every possible path recursively with depth-first search. But since would be repeating calculation of a lot of subpaths, for a large matrix we would receive a TLE (Time limit exceeded ). Now since we are on the right path, how can we optimise this?
Dynamic Programming (Memoization)
We can store the number of paths a matrix element is reachable in a 2D matrix (Memoization). We can only travel right or down thus we can keep adding the paths and the last cell in the DP table would signify the total number of unique paths possible. A Cell DP[i][j] can be possibly reached from the left (DP [i][j – 1]) or top(DP[i – 1][j]). The paths would be zero if the cell is an obstacle (obstacleGrid[i][j] = 0). Since we can only start from (0,0), hence if the first cell is an obstacle then the whole matrix is unreachable and total paths would be 0. We’ll also need to seed the initial starting position with a value of 1 to represent the single initial path. Once we’re done building DP, the value of the bottom-right cell should be our answer.
Since we are iterating through every cell once, the total operations would be equal to the size of the matrix ,ie, N * M. We also storing the paths for every cell and hence space complexity would also of the order of matrix size.
Time = O(N * M), where N = number of rows, M = number of columns
Space = O(N * M)