cztchoice
1/17/2014 - 2:47 PM

## Set Matrix Zeroes http://oj.leetcode.com/problems/set-matrix-zeroes/

``````class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
/*
//This solution use o(m+n) spaces
int m = matrix.size();
if(m == 0){
return;
}
int n = matrix[0].size();
vector<bool> column(m, false);
vector<bool> row(n, false);
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(matrix[i][j] == 0 ){
column[i] = true;
row[j] = true;
}
}
}
for(int i = 0; i < m; i++){
for(int j = 0; j < n; j++){
if(column[i] || row[j] ){
matrix[i][j] = 0;
}
}
}*/
int m = matrix.size();
if(m == 0){
return;
}
int n = matrix[0].size();

bool is_col_0 = false;
bool is_row_0 = false;
for(int i = 0; i < m; i++){
if(matrix[i][0] == 0){
is_col_0 = true;
}
}
for(int j = 0; j < n; j++){
if(matrix[0][j] == 0){
is_row_0 = true;
}
}

for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if( matrix[i][j] == 0 ){
matrix[i][0] = 0;
matrix[0][j] = 0;

}
}
}

for(int i = 1; i < m; i++){
for(int j = 1; j < n; j++){
if(matrix[0][j] == 0 || matrix[i][0] == 0){
matrix[i][j] = 0;
}
}
}
if(is_col_0){
for(int i = 0; i < m; i++){
matrix[i][0] = 0;
}
}
if(is_row_0){
for(int j = 0; j < n; j++){
matrix[0][j] = 0;
}
}
}
};``````