首页 > 代码库 > leetcode 日记

leetcode 日记

1 63. Unique Paths II   带障碍物的路径计算

思路:dp[i][j] = 0 if grid[i][j] = 1 (障碍物)

        再按照无障碍物的逻辑进行计算

技术分享
int uniquePathsWithObstacles(vector<vector<int>>& obstacleGrid) {
        int rows = obstacleGrid.size();
        if (rows == 0) {
            return 0;
        }
        int cols = obstacleGrid[0].size();
        vector<vector<int>> ways(rows, vector<int> (cols, 1));
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (obstacleGrid[i][j] == 1) {
                    ways[i][j] = 0;
                } else {
                    if (i == 0 && j == 0) {
                        ways[i][j] = 1;
                    } else if (i == 0) {
                        ways[i][j] =  ways[i][j - 1];
                    } else if (j == 0) {
                        ways[i][j] = ways[i - 1][j];
                    } else {
                        ways[i][j] = ways[i - 1][j] + ways[i][j - 1];
                    }
                }
            }
        }
        return ways[rows - 1][cols - 1];
    }
View Code

 

 2 矩阵的环形遍历

方法:(1)设置rowStart,rowEnd,colStart,colEnd四个变量来指示当前轮遍历的起始位置

     (2) 按照顺时针方向进行遍历,一轮遍历分成四次循环,每一次循环完成,终点或起点需要缩进一个单位(start + 1,end -1)

注意:当矩阵不是方阵时,需要在每一轮向左和向上遍历之前进行一次判断,否则会造成重复。

技术分享
vector<int> spiralOrder(vector<vector<int>>& matrix) {
        if (matrix.size() == 0) {
            return {};
        }
        int rowStart = 0;
        int rowEnd = matrix.size() - 1;
        int colStart = 0;
        int colEnd = matrix[0].size() - 1;
        vector<int> order;
        while (rowStart <= rowEnd && colStart <= colEnd) {
            for (int j = colStart; j <= colEnd; j++) {
                order.push_back(matrix[rowStart][j]);
            }
            rowStart++;
            for (int i = rowStart; i <= rowEnd; i++) {
                order.push_back(matrix[i][colEnd]);
            }
            colEnd--;
            if (rowStart <= rowEnd) { //注意此处
                for (int j = colEnd; j >= colStart; j--) {
                    order.push_back(matrix[rowEnd][j]);
                }
                rowEnd--;
            }
            if (colStart <= colEnd) {//注意此处
                for (int i = rowEnd; i >= rowStart; i--) {
                    order.push_back(matrix[i][colStart]);
                }
                colStart++;
            }
        }
        return order;
    }
View Code

 

leetcode 日记