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:
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?
思路:这道题要求O(1)的空间复杂度。matrix[i][j]=0可以设置为matrix[i][0]=0和matrix[0][j]=0,即第一行如果有0,则表示该列均为0,第一列如果有0,则表示该行均为0。重新遍历矩阵,按这个规则设置0,其中matrix[0][0]需要特殊考虑,因为它有可能是表示第一行为0,第一列不为0;第一行不为0,第一列为0,;第一行和第一列均为0三种情况。
class Solution {
public:
void setZeroes(vector<vector<int> > &matrix) {
int len = matrix.size();
if (len == 0)
{
return;
}
int m = matrix.size();
int n = matrix[0].size();
int i,j,row=0, col=0;
for(i=0; i<m; ++i)
{
for(j=0; j<n; ++j)
{
if (matrix[i][j] == 0)
{
matrix[i][0] = 0;
matrix[0][j] = 0;
if(i == 0)
{
row = 1;
}
if(j == 0)
{
col = 1;
}
}
}
}
for(i=1; i<m; ++i)
{
if (matrix[i][0] == 0)
{
for(j=1; j<n; ++j)
{
matrix[i][j] = 0;
}
}
}
for(i=1; i<n; ++i)
{
if (matrix[0][i] == 0)
{
for(j=1; j<m; ++j)
{
matrix[j][i] = 0;
}
}
}
if (row == 1)
{
for(i=0; i<n; ++i)
{
matrix[0][i] = 0;
}
}
if(col == 1)
{
for(i=0; i<m; ++i)
{
matrix[i][0] = 0;
}
}
}
};