leetcode63 不同路径2 动态规划

class Solution {
public:
	int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        // 这道题恶心在边界的一些处理上 比如只有一行 或者只有一列,
        // 这一行或者这一列里0和1的排列
        
		if (obstacleGrid.empty()) return 0;
		if (obstacleGrid[0].empty()) return 0;

		int row = obstacleGrid.size();
		int col = obstacleGrid[0].size();
		if (obstacleGrid[0][0] == 1) return 0;
		//if (obstacleGrid[row - 1][col - 1] == 1) return 0;
		vector<vector<int> > dp(row, vector<int>(col, 0));
        // 总是想先把第一行赋值为1, 第一列赋值为1, 但是特殊情况没有考虑到
        // 比如 [[0, 0, 1, 0]]  这样的话 根本就到不了最后一个, 因为中间的1把路封死了
        // 同理 竖着的一列也一样.
        // 因此, 写了很多关于这种情况的处理, 比真正的核心代码还要多
        // 处理横着的一行
		int index = col;
		for (int x = 0; x < col; x++) {
			if (obstacleGrid[0][x] == 1) {
				index = x;
				break;
			}
			dp[0][x] = 1;
		}
		while (index < col) {
			dp[0][index++] = 0;
		}
        // index重新赋值
        // 处理竖着的一列
		index = row;
		for (int y = 0; y < row; y++) {
			if (obstacleGrid[y][0] == 1) {
				index = y;
				break;
			}
			dp[y][0] = 1;
		}
		while (index < row) {
			dp[index++][0] = 0;
		}
		for (int i = 1; i < row; i++) {
			for (int j = 1; j < col; j++) {
				if (obstacleGrid[i][j] == 1) {
					dp[i][j] == 0;

				}
				// from left and from top
				else
					dp[i][j] = dp[i][j - 1] + dp[i - 1][j];
			}
		}
		return dp[row - 1][col - 1];
	}
};

猜你喜欢

转载自blog.csdn.net/weixin_36149892/article/details/80193536
今日推荐