From : https://leetcode.com/problems/set-matrix-zeroes/
Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Solution:
常数空间:
1.考虑是不是固定数量的几个变量能搞定
2.考虑是不是问题本身已经提供了足够的空间
这道题用首行首列。
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
if(matrix.size()==0 || matrix[0].size()==0) return;
int m=matrix.size(), n=matrix[0].size();
bool isRow1Has0=false, isCol1Has0=false;
// init
for(int i=0; i<m; i++) {
if(!matrix[i][0]) {
isCol1Has0 = true;
break;
}
}
for(int j=0; j<n; j++) {
if(!matrix[0][j]) {
isRow1Has0 = true;
break;
}
}
// find ans mark
for(int i=1; i<m; i++) {
for(int j=1; j<n; j++) {
if(!matrix[i][j]) {
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
// set rows
for(int i=1; i<m; i++) {
if(!matrix[i][0]) {
for(int j=1; j<n; j++) {
matrix[i][j] = 0;
}
}
}
// set column
for(int j=1; j<n; j++) {
if(!matrix[0][j]) {
for(int i=1; i<m; i++) {
matrix[i][j] = 0;
}
}
}
// set first row and column
if(isCol1Has0) {
for(int i=0; i<m; i++) matrix[i][0] = 0;
}
if(isRow1Has0) {
for(int j=0; j<n; j++) matrix[0][j] = 0;
}
}
};