Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
Follow up:A straight forward solution using O(mn) space is probably a bad idea.
A simple improvement uses O(m + n) space, but still not the best solution.
Could you devise a constant space solution?
Did you use extra space?
Solution:
void setZeroes(vector<vector<int> > &matrix) {
bool rowflag = false;
bool columnflag = false;
if(matrix.size()==0)
return;
for(int i=0;i<matrix.size();i++)
{
if(matrix[i][0]==0)
{
columnflag = true;
}
}
for(int j=0;j<matrix[0].size();j++)
{
if(matrix[0][j]==0)
{
rowflag = true;
}
}
for(int i=1;i<matrix.size();i++)
{
for(int j=1;j<matrix[0].size();j++)
{
if(matrix[i][j]==0)
{
matrix[i][0] = 0;
matrix[0][j] = 0;
}
}
}
for(int i=1;i<matrix.size();i++)
{
for(int j=1;j<matrix[0].size();j++)
{
if(matrix[0][j]==0||matrix[i][0]==0)
{
matrix[i][j] = 0;
}
}
}
if(columnflag)
{
for(int i=0;i<matrix.size();i++)
{
matrix[i][0]=0;
}
}
if(rowflag)
{
for(int j=0;j<matrix[0].size();j++)
{
matrix[0][j]=0;
}
}
}
No comments:
Post a Comment