Leetcode 62: Unique Paths

Problem Link: https://leetcode.com/problems/unique-paths/


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).
How many possible unique paths are there?
Above is a 7 x 3 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Example 1:
Input: m = 3, n = 2
Output: 3
Explanation:
From the top-left corner, there are a total of 3 ways to reach the bottom-right corner:
1. Right -> Right -> Down
2. Right -> Down -> Right
3. Down -> Right -> Right
Example 2:
Input: m = 7, n = 3
Output: 28

Solution:

Suppose we are at any cell (i, j). Then ,  the number of ways to reach the cell (i, j) is the sum of number of ways to reach cell (i - 1, j) (above) and (i, j - 1) (left) i.e
          numways(i, j) = numways(i - 1, j) + numways(i, j - 1) 

Instead of using recursive approach I'm gonna use bottom up dp to solve the problem.
Let's say dp[i][j] gives the number of ways to reach cell (i, j).
Then,
          dp[i][j] = dp[i - 1][j] + dp[i][j - 1]

Let's see the first row and first column.
What is the number of ways to reach any cell (i, 0) or (0, j) ???
There is only one way to reach cell (i, 0) i.e only from upward direction i.e cell (i - 1, 0).
So,
          dp[i][0] = 1 
Similarly, there is only one way to reach cell (0, j) i.e only from left direction i.e cell (0, j - 1).
So,
          dp[0][j] = 1 

Implementation:

 class Solution {
public:
    int uniquePaths(int m, int n) {
     
     // dp[i][j]  gives the number of ways to reach cell (i, j)
        int dp[m][n];
        
        // There is only 1 way to reach any cell at first column i.e
        // from the cell upward 
        // So dp[i][0] = 1
        for(int i = 0; i < m; i++){
            dp[i][0] = 1;
        }
        
        
        // There is only 1 way to reach any cell at first row i.e
        // from the cell left 
        // So dp[0][j] = 1
        for(int i = 0; i < n; i++){
            dp[0][i] = 1;
        }
        
        
        // For all cells (i, j) from (1, 1) to (m - 1, n - 1)
        // we build the table in bottom up manner
        // We can reach any cell (i, j) from (i - 1, j) or (i, j - 1)
        // So dp[i][j] = dp[i - 1][j] + dp[i][j - 1]
        for(int i = 1; i < m; i++){
            for(int j = 1; j < n; j++){
                dp[i][j]  = dp[i - 1][j] + dp[i][j - 1];
            }
        }
        
        // Return number of ways to reach cell (m - 1, n - 1)
        return dp[m - 1][n - 1];
        
    }
};
Here is a slightly modified version of this problem: https://leetcode.com/problems/unique-paths-ii/

Share:

0 comments:

Post a Comment