[LeetCode]Set Matrix Zeroes

来源:互联网 发布:淘宝优惠券的评价软件 编辑:程序博客网 时间:2024/04/29 21:28
class Solution {//let the first row and first col to keep the record//if matrix[row][col] == 0 && col == 0, then firstColZero = true, same to firstRowZeropublic:void setZeroes(vector<vector<int> > &matrix) {// Start typing your C/C++ solution below// DO NOT write int main() functionint rowNum = matrix.size();if(0 == rowNum) return;int colNum = matrix[0].size();bool firstRowZero, firstColumnZero;firstRowZero = firstColumnZero = false;for (int row = 0; row < rowNum; ++row){for (int col = 0; col < colNum; ++col){if (!matrix[row][col]){if(row == 0) firstRowZero = true;if(col == 0) firstColumnZero = true;matrix[row][0] = 0;matrix[0][col] = 0;}}}//according the flag in first row and first col to set the row and col to zero correspondingfor(int row = 1; row < rowNum; ++row){if(0 == matrix[row][0]){for (int col = 0; col < colNum; ++col)matrix[row][col] = 0;}}//for(int col = 1; col < colNum; ++col){if(0 == matrix[0][col]){for (int row = 0; row < rowNum; ++row)matrix[row][col] = 0;}}//if(firstRowZero)for (int col = 0; col < colNum; ++col)matrix[0][col] = 0;if(firstColumnZero)for (int row = 0; row < rowNum; ++row)matrix[row][0] = 0;}};

second time

class Solution {public:    void setZeroes(vector<vector<int> > &matrix) {// Start typing your C/C++ solution below// DO NOT write int main() functionint n = matrix.size();if(n == 0) return;int m = matrix[0].size();if(m == 0) return;bool firstRow = false;bool firstColumn = false;for(int i = 0; i < n; ++i) {if(matrix[i][0] == 0){firstColumn = true;break;}}for(int j = 0; j < m; ++j) {if(matrix[0][j] == 0){firstRow = true;break;}}//using first row and first column to keep recordfor(int i = 1; i < n; ++i){for(int j = 1; j < m; ++j){if(matrix[i][j] == 0) matrix[0][j] = 0, matrix[i][0] = 0;}}//set zerofor(int i = 1; i < n; ++i){if(matrix[i][0] == 0) {for(int j = 1; j < m; ++j) matrix[i][j] = 0;}}for(int j = 1; j < m; ++j){if(matrix[0][j] == 0){for(int i = 1; i < n; ++i) matrix[i][j] = 0;}}//set first row and first columif(firstRow) {for(int j = 0; j < m; ++j) matrix[0][j] = 0;}if(firstColumn){for(int i = 0; i < n; ++i) matrix[i][0] = 0;}}};


原创粉丝点击