Cover image for Interview Classic 150 Questions P63 Unique Paths II

Interview Classic 150 Questions P63 Unique Paths II


Timeline

Timeline

2025-12-13

init

Dynamic Programming

Problem:

Note that the special case when mn1 should be considered.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
#include <vector>using std::vector;class Solution {    public:        int uniquePathsWithObstacles(vector<vector<int> > &obstacleGrid)        {                int i, j, m = obstacleGrid.size(), n = obstacleGrid[0].size();                if (m == 1 && n == 1) {                        if (obstacleGrid[0][0] == 1) {                                return 0;                        }else{                                return 1;                        }                }                // dp[i][j] represents the number of different paths to reach grid[i][j].                vector<vector<int> > dp(m, vector<int>(n, 0));                dp[0][0] = 1;                for (i = 1; i < m; i++) {                        if (obstacleGrid[i - 1][0] != 1 &&                            obstacleGrid[i][0] != 1) {                                dp[i][0] = 1;                        } else {                                break;                        }                }                for (j = 1; j < n; j++) {                        if (obstacleGrid[0][j - 1] != 1 &&                            obstacleGrid[0][j] != 1) {                                dp[0][j] = 1;                        } else {                                break;                        }                }                for (i = 1; i < m; i++) {                        for (j = 1; j < n; j++) {                                if (obstacleGrid[i][j] == 1) {                                        continue;                                }                                if (obstacleGrid[i - 1][j] == 1 &&                                    obstacleGrid[i][j - 1] == 1) {                                        continue; // set default as 0                                } else if (obstacleGrid[i - 1][j] == 1 &&                                           obstacleGrid[i][j - 1] == 0) {                                        dp[i][j] = dp[i][j - 1];                                } else if (obstacleGrid[i - 1][j] == 0 &&                                           obstacleGrid[i][j - 1] == 1) {                                        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];        }};
Loading comments…