您的位置:首页 > 产品设计 > UI/UE

Unique Paths II

2013-10-03 03:42 387 查看
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,则没有路径。

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
// Note: The Solution object is instantiated only once and is reused by each test case.
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] num = new int[m]
;
num[0][0] = 1;
if(obstacleGrid[0][0] == 1 || obstacleGrid[m - 1][n - 1] == 1)
{
return 0;
}
for(int i = 0; i < m; i ++)
{
for(int j = 0; j < n; j ++)
{
if(i > 0 && obstacleGrid[i - 1][j] != 1) num[i][j] += num[i - 1][j];
if(j > 0 && obstacleGrid[i][j - 1] != 1) num[i][j] += num[i][j - 1];
}
}
return num[m - 1][n - 1];
}
}


第三遍:

public class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if(obstacleGrid == null || obstacleGrid.length == 0 || obstacleGrid[0].length == 0) return 0;
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
int[][] matrix = new int[m]
;
matrix[m - 1][n - 1] = obstacleGrid[m - 1][n - 1] == 1 ? 0 : 1;
for(int i = m - 2; i > -1; i --)
matrix[i][n - 1] = obstacleGrid[i][n - 1] == 1 ? 0 : matrix[i + 1][n - 1];
for(int i = n - 2; i > -1; i --)
matrix[m - 1][i] = obstacleGrid[m - 1][i] == 1 ? 0 : matrix[m - 1][i + 1];
if(matrix[0][0] == -1) return 0;
for(int i = m - 2; i > -1; i --)
for(int j = n - 2; j > -1; j --)
matrix[i][j] = obstacleGrid[i][j] == 1 ? 0 : matrix[i + 1][j] + matrix[i][j + 1];
return matrix[0][0];
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: