63. The different paths II
A robot located in a left corner mxn grid (starting point figure below labeled "Start").
The robot can only move one step to the right or down. Robot trying to reach the bottom right corner of the grid (in the following figure labeled "Finish").
Now consider the grid obstructions. So how many different paths from top left to bottom right corner there will be?
Empty grid positions and the obstacle respectively 1 and 0 to represent.
Description: the values of m and n is not more than 100.
Example 1:
Input:
[
[0,0,0],
[0,1,0],
[0,0,0]
]
Output: 2
Explanation:
in the middle has a 3x3 grid obstacle.
From top left to bottom right corner of a total of two different paths:
- Right -> Right -> Down -> Down
- Down -> Down -> right -> right
Source: stay button (LeetCode)
link: https: //leetcode-cn.com/problems/unique-paths-ii
copyrighted by deduction from all networks. Commercial reprint please contact the authorized official, non-commercial reprint please indicate the source.
class Solution {
public int uniquePathsWithObstacles(int[][] arr) {
if (arr == null || arr.length <= 0) {
return 0;
}
int rows = arr.length;
int cols = arr[0].length;
int[][] dp = new int[rows][cols];
for (int i = 0; i < cols; i++)
if (arr[0][i] == 1) {
dp[0][i] = 0;
break; // 遇到障碍后面的都无法到达直接返回就行 默认就是0
}
else dp[0][i] = 1;
for (int i = 0; i < rows; i++)
if (arr[i][0] == 1) {
dp[i][0] = 0;
break; // 遇到障碍后面的都无法到达直接返回就行 默认就是0
}
else dp[i][0] = 1;
for (int i = 1; i < rows; i++) {
for (int j = 1; j < cols; j++) {
if (arr[i][j] == 1) dp[i][j] = 0; // 遇到障碍就是0
else dp[i][j] = dp[i - 1][j] + dp[i][j - 1]; // dpdpdp
}
}
return dp[rows - 1][cols - 1];
}
}