题目描述
Follow up: Did you use extra space?
A straight forward solution using O(m n) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
const int row=matrix.size();
const int col=matrix[0].size();
bool row_flag=false,col_flag=false;
for (int i=0;i<row ;i++)
if (0==matrix [i][0])
{
col_flag=true;
break;
}
for (int i=0;i<col;i++)
if (0==matrix[0][i])
{
row_flag=true;
break;
}
for (int i=1;i<row;i++)
for (int j=1;j<col;j++)
if (0==matrix[i][j]){
matrix[i][0]=0;
matrix[0][j]=0;
}
for (int i=1;i<row;i++){
for (int j=1;j<col;j++){
if (0==matrix[i][0] || matrix [0][j]==0)
matrix[i][j]=0;
}
}
if (row_flag)
for (int i=0;i<col;i++)
matrix[0][i]=0;
if (col_flag)
for (int i=0;i<row;i++)
matrix[i][0]=0;
}
};