Swift Leetcode Series: Unique Paths II

Swift + Dynamic Programming = Leetcode 63 ✅ ✅ ✅

Varun
Nerd For Tech

--

You can also read the full story on The Swift Nerd blog along with other interesting stories by clicking the link above.

Problem Description

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 1 and 0 respectively in the grid.

Example 1:

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

Example 2:

Input: obstacleGrid = [[0,1],[0,0]]
Output: 1

Constraints

  • m == obstacleGrid.length
  • n == obstacleGrid[i].length
  • 1 <= m, n <= 100
  • obstacleGrid[i][j] is 0 or 1.

Solution

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.

Code

Complexity Analysis

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)

Thank you for reading. If you liked this article and found it useful, share and spread it like wildfire!

You can find me on TheSwiftNerd | LinkedIn | Github

--

--