Unique Paths II (M)
題目
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
題意
在矩形中找到一條路徑,起點為左上頂點,終點為右下頂點,路徑中只能向右或向下走,且矩形中存在不能通過的障礙點,要求統計不同路徑的個數,
思路
與 0062. Unique Paths (M) 方法一致,只是多了障礙點不好用組合數解決問題,使用動態規劃,并用滾動陣列進行優化,
代碼實作
Java
動態規劃
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length, m = obstacleGrid[0].length;
int[][] dp = new int[n][m];
dp[0][0] = obstacleGrid[0][0] == 1 ? 0 : 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
if (i != 0 || j != 0) {
dp[i][j] = obstacleGrid[i][j] == 1 ? 0 :
((i == 0 ? 0 : dp[i - 1][j]) + (j == 0 ? 0 : dp[i][j - 1]));
}
}
}
return dp[n - 1][m - 1];
}
}
滾動陣列優化
class Solution {
public int uniquePathsWithObstacles(int[][] obstacleGrid) {
int n = obstacleGrid.length, m = obstacleGrid[0].length;
int[] dp = new int[m];
dp[0] = 1;
for (int i = 0; i < n; i++) {
for (int j = 0; j < m; j++) {
dp[j] = obstacleGrid[i][j] == 1 ? 0 : j > 0 ? dp[j - 1] + dp[j] : dp[j];
}
}
return dp[m - 1];
}
}
JavaScript
/**
* @param {number[][]} obstacleGrid
* @return {number}
*/
var uniquePathsWithObstacles = function (obstacleGrid) {
let n = obstacleGrid.length
let m = obstacleGrid[0].length
let scroll = new Array(m).fill(0)
scroll[0] = 1
for (let i = 0; i < n; i++) {
for (let j = 0; j < m; j++) {
if (obstacleGrid[i][j] === 1) {
scroll[j] = 0
} else {
scroll[j] = j === 0 ? scroll[j] : scroll[j] + scroll[j - 1]
}
}
}
return scroll[m - 1]
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/21317.html
標籤:其他
