玩命加载中 . . .

73-矩阵置零


LeetCode 73. Set Matrix Zeroes

LeetCode-73

Given an m x n integer matrix matrix, if an element is 0, set its entire row and column to 0's, and return the matrix.

You must do it in place.

Example 1:

Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
Output: [[1,0,1],[0,0,0],[1,0,1]]

Example 2:

Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]

method

如果matrix[i][j]为零,就把matrix[i][0]matrix[0][j]置零,后面再遍历的时候就看matrix[i][0]matrix[0][j]决定是否将元素置零

但是matrix[0][0]会出现混淆,无法确定是第0行还是第0列导致的置零,所以用两个变量来特判

void setZeroes(vector<vector<int>>& matrix) {
    int n = matrix.size(), m = matrix[0].size();
    bool row0 = false, col0 = false;
    for (int i = 0; i < n; i++) {
        if (matrix[i][0] == 0) {    // 查看第一列
            col0 = true;
            break;
        }
    }
    for (int j = 0; j < m; j++) {
        if (matrix[0][j] == 0) {    // 查看第一行
            row0 = true;
            break;
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            if (matrix[i][j] == 0) {
                matrix[i][0] = 0;   // i行首元素置0
                matrix[0][j] = 0;   // j列首元素置0
            }
        }
    }
    for (int i = 1; i < n; i++) {
        for (int j = 1; j < m; j++) {
            if (matrix[i][0] == 0 || matrix[0][j] == 0)
                matrix[i][j] = 0;   // 行首或列首是0就置0
        }
    }
    for (int i = 0; i < n; i++) {
        if (col0) matrix[i][0] = 0; // 处理第一列
    }
    for (int j = 0; j < m; j++) {
        if (row0) matrix[0][j] = 0; // 处理第一行
    }
}

文章作者: kunpeng
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 kunpeng !
  目录