62. Unique Paths && 63. Unique Paths II
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 3 x 7 grid. How many possible unique paths are there?
Note: m and n will be at most 100.
Subscribe to see which companies asked this question
Hide Similar Problems
public class Solution { public int uniquePaths(int m, int n) { int[][] count = new int[m][]; for(int i = 0; i<m; ++i) { count[i] = new int[n]; count[i][0] = 1; } for(int i = 0; i<n; ++i) { count[0][i] = 1; } for(int r = 1; r<m; ++r) for(int c = 1; c<n; ++c) count[r][c] = count[r][c-1] + count[r-1][c]; return count[m-1][n-1]; } }
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.
For example,
There is one obstacle in the middle of a 3x3 grid as illustrated below.
[ [0,0,0], [0,1,0], [0,0,0] ]
The total number of unique paths is 2.
Note: m and n will be at most 100.
Subscribe to see which companies asked this question
Hide Similar Problems
public class Solution { public int uniquePathsWithObstacles(int[][] obstacleGrid) { if(obstacleGrid[0][0] == 1) //This is very important and fixes bugs. return 0; int row = obstacleGrid.length; int col = obstacleGrid[0].length; boolean firstColumnOb = false; for(int r = 0; r<row; ++r) { for(int c = 0;c<col; ++c) { if(r == 0) { if(obstacleGrid[r][c] == 0) obstacleGrid[r][c] = 1; else { for(;c<col; ++c) { obstacleGrid[r][c] = 0; } } } else if(c == 0) { if(!firstColumnOb && obstacleGrid[r][c] == 0) obstacleGrid[r][c] = 1; else { firstColumnOb = true; obstacleGrid[r][c] = 0; } } else { if(obstacleGrid[r][c] == 0) obstacleGrid[r][c] = obstacleGrid[r-1][c] + obstacleGrid[r][c-1]; else obstacleGrid[r][c] = 0; } } } return obstacleGrid[row-1][col-1]; } }

浙公网安备 33010602011771号