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.
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.
很简单的DP, 但是要注意,如果起点或者终点为obstacle,则没有路径。
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 // Note: The Solution object is instantiated only once and is reused by each test case. 4 if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 5 int m = obstacleGrid.length; 6 int n = obstacleGrid[0].length; 7 int[][] num = new int[m][n]; 8 num[0][0] = 1; 9 if(obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1) 10 { 11 return 0; 12 } 13 for(int i = 0; i < m; i ++) 14 { 15 for(int j = 0; j < n; j ++) 16 { 17 if(i > 0 && obstacleGrid[i - 1][j] != 1) num[i][j] += num[i - 1][j]; 18 if(j > 0 && obstacleGrid[i][j - 1] != 1) num[i][j] += num[i][j - 1]; 19 } 20 } 21 return num[m - 1][n - 1]; 22 } 23 }
第三遍:
1 public class Solution { 2 public int uniquePathsWithObstacles(int[][] obstacleGrid) { 3 if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0; 4 int m = obstacleGrid.length; 5 int n = obstacleGrid[0].length; 6 int[][] matrix = new int[m][n]; 7 matrix[m - 1][n - 1] = obstacleGrid[m - 1][n - 1] == 1 ? 0 : 1; 8 for(int i = m - 2; i > -1; i --) 9 matrix[i][n - 1] = obstacleGrid[i][n - 1] == 1 ? 0 : matrix[i + 1][n - 1]; 10 for(int i = n - 2; i > -1; i --) 11 matrix[m - 1][i] = obstacleGrid[m - 1][i] == 1 ? 0 : matrix[m - 1][i + 1]; 12 if(matrix[0][0] == -1) return 0; 13 for(int i = m - 2; i > -1; i --) 14 for(int j = n - 2; j > -1; j --) 15 matrix[i][j] = obstacleGrid[i][j] == 1 ? 0 : matrix[i + 1][j] + matrix[i][j + 1]; 16 return matrix[0][0]; 17 } 18 }
posted on 2013-10-03 03:42 Step-BY-Step 阅读(152) 评论(0) 编辑 收藏 举报