解题思路和代码:
#include <iostream>
#include <vector>
using namespace std;
void setZeroes_bit(vector<vector<int>>& matrix)
{
if(matrix.empty()) return;
int rowflag = 0;
int columnflag = 0;
int rowsize = matrix.size();
int columnsize = matrix[0].size();
for(int i = 0; i < rowsize ; i++)
{
for(int j = 0; j < columnsize; j++)
{
if(matrix[i][j] == 0)
{
if((rowflag | 1 << i) != rowflag)
{
rowflag |= 1 << i;
}
if((columnflag | 1 << j) != columnflag)
{
columnflag |= 1 << j;
}
}
}
}
for(int j = 0; j < columnsize; j++)
{
if((columnflag | 1 << j) == columnflag)
{
for(int i = 0; i < rowsize ; i++)
{
matrix[i][j] = 0;
}
}
}
for(int i = 0; i < rowsize; i++)
{
if((rowflag | 1 << i) == rowflag)
{
for(int j = 0; j < columnsize; j++)
{
if((columnflag | 1 << j) != columnflag)
{
matrix[i][j] = 0;
}
}
}
}
}
void setZeroes_bool(vector<vector<int>>& matrix)
{
if(matrix.empty()) return;
int rowsize = matrix.size();
int columnsize = matrix[0].size();
vector<bool> rowflag(rowsize);
vector<bool> columnflag(columnsize);
for(int i = 0; i < rowsize ; i++)
{
for(int j = 0; j < columnsize; j++)
{
if(matrix[i][j] == 0)
{
if(rowflag[i] != 1)
{
rowflag[i] = 1;
}
if(columnflag[j] != 1)
{
columnflag[j] = 1;
}
}
}
}
for(int j = 0; j < columnsize; j++)
{
if(columnflag[j] == 1)
{
for(int i = 0; i < rowsize ; i++)
{
matrix[i][j] = 0;
}
}
}
for(int i = 0; i < rowsize; i++)
{
if(rowflag[i] == 1)
{
for(int j = 0; j < columnsize; j++)
{
if(columnflag[j] != 1)
{
matrix[i][j] = 0;
}
}
}
}
}
void print(vector<vector<int>> matrix)
{
int rowsize = matrix.size();
int columnsize = matrix[0].size();
for(int i = 0; i < rowsize; i++)
{
cout << "[";
for(int j = 0; j < columnsize - 1; j++)
{
cout << matrix[i][j] << ",";
}
cout << matrix[i][columnsize - 1] << "]\n";
}
cout << endl;
}
int main()
{
vector<vector<int>> matrix = {{1,1,1},{1,0,1},{1,1,1}};
print(matrix);
setZeroes_bool(matrix);
print(matrix);
vector<vector<int>> matrix1 = {{0,1,2,0},{3,4,5,2},{1,3,1,5}};
print(matrix1);
setZeroes_bool(matrix1);
print(matrix1);
vector<vector<int>> matrix2 = {{0,1}};
print(matrix2);
setZeroes_bool(matrix2);
print(matrix2);
vector<vector<int>> matrix3 = {{0,0,0,5},{4,3,1,4},{0,1,1,4},{1,2,1,3},{0,0,1,1}};
print(matrix3);
setZeroes_bool(matrix3);
print(matrix3);
return 0;
}