Description Link to heading
Solution Link to heading
Compared with 62.unique-paths, the main difference is that you need to change $dp_{mn}$ when hitting an obstacle(obstacleGrid[i][j] = 0). Just set dp[i][j] = 0.
And you need pay attention to judging the conditionality in for loop.
When i = 0 or j = 0, dp[i][j] = dp[i][j - 1] or dp[i][j] = dp[i - 1][j]. dp[0][0] = 0.
Code Link to heading
#include <vector>
using std::vector;
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>> &obstacleGrid) {
int m = obstacleGrid.size();
int n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
dp[0][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (i == 0 && j == 0) {
if (obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else
dp[i][j] = 1;
} else {
if (obstacleGrid[i][j] == 1)
dp[i][j] = 0;
else {
if (i == 0)
dp[i][j] = dp[i][j - 1];
else if (j == 0)
dp[i][j] = dp[i - 1][j];
else
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}
}
}
return dp[m - 1][n - 1];
}
};