A Pilgrimage — LeetCode Punch Day 39
knowledge summary
Dynamic programming problem with different paths
Leetcode 62. Different paths
topic description
A robot is located in the upper left corner of an mxn grid (the starting point is marked "Start" in the figure below).
The robot can only move one step down or to the right at a time. The robot tries to reach the bottom right corner of the grid (marked "Finish" in the image below).
How many different paths are there in total?
code description
The recursion formula is:
dp[i][j] = dp[i-1][j] + dp[i][j-1];
class Solution {
public int uniquePaths(int m, int n) {
int[][] dp = new int[m][n];
for(int i =0; i < m; i++){
for(int j =0; j < n; j++){
if(i == 0 || j == 0){
dp[i][j] = 1;
}else{
dp[i][j] = dp[i-1][j] + dp[i][j-1];
}
}
}
return dp[m-1][n-1];
}
}
Leetcode 63. Different Paths II
topic description
A robot is located in the upper left corner of an mxn grid (the starting point is marked "Start" in the figure below).
The robot can only move one step down or to the right at a time. The robot tries to reach the bottom right corner of the grid (marked "Finish" in the image below).
Now consider that there are obstacles in the grid. So how many different paths will there be from top left to bottom right?
Obstacles and empty positions in the grid are represented by 1 and 0, respectively.
code description
normal version;
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[][] dp = new int[m][n];
if(obstacleGrid[0][0] == 1){
return 0;
}
dp[0][0] = 1;
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(obstacleGrid[i][j] == 1){
dp[i][j] = 0;
}else{
if(i == 0 & j == 0) continue;
int upWay =0;
int leftWay = 0;
if(i> 0){
upWay = dp[i-1][j];
}
if(j > 0){
leftWay = dp[i][j-1];
}
dp[i][j] = upWay + leftWay;
}
}
}
return dp[m-1][n-1];
}
}
Space optimized version:
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length, n = obstacleGrid[0].length;
int[] dp = new int[n];
if(obstacleGrid[0][0] == 1 || obstacleGrid[m-1][n-1] == 1){
return 0;
}
for(int i = 0; i < n && obstacleGrid[0][i] == 0; i++){
dp[i] = 1;
}
for(int i = 1; i < m; i++){
for(int j = 0; j < n; j++){
if (obstacleGrid[i][j] == 1){
dp[j] = 0;
}else if (j > 0){
dp[j] += dp[j-1];
}
}
}
return dp[n-1];
}
}