编写一种算法,若M × N矩阵中某个元素为0,则将其所在的行与列清零。
示例
输入:
[
[0,1,2,0],
[3,4,5,2],
[1,3,1,5]
]
输出:
[
[0,0,0,0],
[0,4,5,0],
[0,3,1,0]
]
开辟一个新的bool数组
class Solution {
public:
void setZeroes(vector<vector<int>>& matrix) {
int mRow = matrix.size();
int mCol = matrix[0].size();
if(mRow == 0 || mCol == 0)
{
return;
}
vector<bool> row(mRow, false);
vector<bool> col(mCol, false);
for(int i = 0; i < mRow; i++)
{
for(int j = 0; j < mCol; j++)
{
if(matrix[i][j] == 0)
{
row[i] = true;
col[j] = true;
}
}
}
for(int i = 0; i < mRow; i++)
{
for(int j = 0; j < mCol; j++)
{
if(row[i] || col[j])
{
matrix[i][j] = 0;
}
}
}
return;
}
};