面试题 08.02
Solutions
class Solution {
public:
enum Direction {RIGHT = 1, DOWN = 2};
vector<vector<int>> pathWithObstacles(vector<vector<int>>& obstacleGrid) {
int m = obstacleGrid.size(); if (!m) return {};
int n = obstacleGrid[0].size();
if (obstacleGrid[0][0] == 1) return {};
// dynamic programming with dp transitions recorded
vector<vector<int>> dp(m, vector<int>(n));
dp[0][0] = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (obstacleGrid[i][j])
dp[i][j] = 0;
else if (i > 0 && dp[i - 1][j])
dp[i][j] = DOWN;
else if (j > 0 && dp[i][j - 1])
dp[i][j] = RIGHT;
}
}
int i = m - 1, j = n - 1;
vector<vector<int>> res;
// backtracking from the bottom right point, find a valid path.
if (dp[i][j] != 0) {
while (j >= 0) {
res.push_back({i, j});
(dp[i][j] == RIGHT ? j : i)--;
}
reverse(res.begin(), res.end());
}
return res;
}
};Last updated