描述:
从左上角走到右下角,中间可能有若干阻碍;
题目给出一个矩阵,0表示可以走,1表示有障碍。
解决:
思路同第一题,只是如果上面或左边有障碍,自身不一定能走,注意些边界条件即可,复杂度仍是m*n。
为了防止和真正的路径1冲突,走过的障碍改为-1。
int uniquePathsWithObstacles(vector>& obstacleGrid) { int m = obstacleGrid.size(); int n = obstacleGrid[0].size(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { if (obstacleGrid[i][j] == 1) { obstacleGrid[i][j] = -1; continue; } if (i == 0 && j == 0) obstacleGrid[0][0] = 1; else if (i == 0) obstacleGrid[0][j] = obstacleGrid[0][j - 1]; else if (j == 0) obstacleGrid[i][0] = obstacleGrid[i - 1][0]; else if (obstacleGrid[i - 1][j] == -1 && obstacleGrid[i][j - 1] == -1) obstacleGrid[i][j] = -1; else if (obstacleGrid[i - 1][j] == -1) obstacleGrid[i][j] = obstacleGrid[i][j - 1]; else if (obstacleGrid[i][j - 1] == -1) obstacleGrid[i][j] = obstacleGrid[i - 1][j]; else if (obstacleGrid[i][j] == 1) obstacleGrid[i][j] = -1; else obstacleGrid[i][j] = obstacleGrid[i - 1][j] + obstacleGrid[i][j - 1]; } } if (obstacleGrid[m - 1][n - 1] == -1) return 0; return obstacleGrid[m - 1][n - 1];}