[LeetCode] Unique Paths II

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 space is marked as 1 and 0 respectively in the grid.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
class Solution {
public:
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(), n = obstacleGrid[0].size();
vector<vector<int>> dp(m, vector<int>(n, 0));
for(int i = 0; i < n && !obstacleGrid[0][i]; i++) {
dp[0][i] = 1;
}
for(int i = 0; i < m && !obstacleGrid[i][0]; i++) {
dp[i][0] = 1;
}
for(int i = 1; i < m; i++) {
for(int j = 1; j < n; j++) {
if(obstacleGrid[i][j]) continue;
dp[i][j] = dp[i - 1][j] + dp[i][j - 1];
}
}

return dp[m-1][n-1];
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/06/PS/LeetCode/unique-paths-ii/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.