07/10 00:16

# 题目： 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).

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.

Note: m and n will be at most 100.

Example 1:

```Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
There is one obstacle in the middle of the 3x3 grid above.
There are two ways to reach the bottom-right corner:
1. Right -> Right -> Down -> Down
2. Down -> Down -> Right -> Right```

# 最终实现

Java 实现

``````// Input: [[1]]
// Expected: 0
public class Solution {

private int h[][];

public int uniquePathsWithObstacles(int[][] obstacleGrid) {
if (null == obstacleGrid || obstacleGrid.length <= 0) {
return 0;
}
int m = obstacleGrid.length;
int n = obstacleGrid[0].length;
// initialize the two-dimension array h
h = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
h[i][j] = obstacleGrid[i][j] != 1 ? -1 : 0;
}
}
// return 0 because the right-bottom position is blocked
if (h[m-1][n-1] == 0) {
return 0;
}
// set the right-bottom position to 1
h[m-1][n-1] = 1;
return calcH(0, 0);
}

private int calcH(int i, int j) {
int m = h.length;
int n = h[0].length;
if (i >= m || j >= n) {
return 0;
}
if (h[i][j] != -1) {
return h[i][j];
}
h[i][j] = calcH(i + 1, j) + calcH(i, j + 1);
return h[i][j];
}

public static void main(String[] args) {
Solution solution = new Solution();
int m = 1;
int n = 1;
int[][] obstacleGrid = new int[m][n];
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
obstacleGrid[i][j] = 0;
}
}
obstacleGrid[0][0] = 1;
int res = solution.uniquePathsWithObstacles(obstacleGrid);
System.out.println(res);
}

}
``````

0
0 收藏

0 评论
0 收藏
0