Unique Paths
lc 62
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?
public class Solution {
public int uniquePaths(int m, int n) {
int[][] result = new int[m][n];
result[0][0] = 1;
for (int i = 1; i < n; i++){
result[0][i] = 1;
}
for (int j = 1; j < m; j++){
result[j][0] = 1;
}
for(int i = 1; i < m; i++ ){
for (int j = 1; j < n ;j++){
result[i][j] = result[i-1][j] + result[i][j-1];
}
}
return result[m-1][n-1];
}
}
lc 63 Unique Paths II
Follow up for "Unique Paths":
Now consider if some obstacles are added to the grids. How many unique paths would there be?
An obstacle and empty space is marked as 1 and 0 respectively in the grid.
[
[0,0,0],
[0,1,0],
[0,0,0]
]
The total number of unique paths is 2.
public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] result = new int[m][n];
if (obstacleGrid[0][0] == 1) return 0;
result[0][0] = 1;
for (int i = 1; i < n; i++){
if (obstacleGrid[0][i] == 1)
break;
result[0][i] = 1;
}
for (int j = 1; j < m; j++){
if (obstacleGrid[j][0] == 1)
break;
result[j][0] = 1;
}
for(int i = 1; i < m; i++ ){
for (int j = 1; j < n ;j++){
if (obstacleGrid[i][j] == 1)
result[i][j] = 0;
else
result[i][j] = result[i-1][j] + result[i][j-1];
}
}
return result[m-1][n-1];
}
}