LeetCode 73. Set Matrix Zeroes

来源:互联网 发布:淘宝开店缴纳保证金 编辑:程序博客网 时间:2024/06/07 22:58

Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.

// Only provides in-place method. The trick is to remember the 0s in the first row and first column.

 void setZeroes(vector<vector<int>>& matrix) {    if(matrix.size() == 0) return;    if(matrix[0].size() == 0) return;    int rows = matrix.size();    int cols = matrix[0].size();    bool rowZero = false;    bool colZero = false;        for(int i = 0; i < cols; ++i) {        if(matrix[0][i] == 0) {            rowZero = true;            break;        }    }    for(int j = 0; j < rows; ++j) {        if(matrix[j][0] == 0) {            colZero = true;            break;        }    }    for(int i = 1; i < rows; ++i) {        for(int j = 1; j < cols; ++j) {            if(matrix[i][j] == 0) {                matrix[i][0] = 0;                matrix[0][j] = 0;  // remember to 0s to the first row and first column.            }        }    }    for(int i = 1; i < rows; ++i) {        for(int j = 1; j < cols; ++j) {            if(matrix[i][0] == 0 || matrix[0][j] == 0) {                matrix[i][j] = 0;  // apply them back.            }        }    }    if(rowZero) {        for(int i = 0; i < cols; ++i) {            matrix[0][i] = 0;        }    }    if(colZero) {        for(int i = 0; i < rows; ++i) {            matrix[i][0] = 0;        }    }}


0 0
原创粉丝点击