题目:Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in place.
click to show follow up.
Follow up:
Did you use extra space?
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?
题意:给定一个矩阵,若矩阵中有个元素为0,则将其所在行和列的所有元素置0
解法:采用递归完成,判断当前位置的行和列是否应该置0,然后递归下一行和下一列,直到最后,递归完成后,再对矩阵中的元素置0
void setZeroesCore(vector<vector<int>>& matrix,int row,int col,int rows,int cols)
{
if(row>=rows||col>=cols)return;
bool rowflag=false;
bool colflag=false;
for(int i=0;i<cols;i++)
{
if(matrix[row][i]==0)
{
rowflag=true;
break;
}
}
for(int i=0;i<rows;i++)
{
if(matrix[i][col]==0)
{
colflag=true;
break;
}
}
if(col<cols-1||row<rows-1)
{
int col1=col;
int row1=row;
if(col<cols-1)col1++;
if(row<rows-1)row1++;
setZeroesCore(matrix,row1,col1,rows,cols);
}
if(rowflag)
{
for(int i=0;i<cols;i++)
{
matrix[row][i]=0;
}
}
if(colflag)
{
for(int i=0;i<rows;i++)
{
matrix[i][col]=0;
}
}
}
void setZeroes(vector<vector<int>>& matrix) {
int m=matrix.size();
if(m==0)return;
int n=matrix[0].size();
setZeroesCore(matrix,0,0,m,n);
}