题目描述
请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。
给定一个N阶方阵int[][](C++中为vector<vector><int>>)mat和矩阵的阶数n,请返回完成操作后的int[][]方阵(C++中为vector<vector><int>>),保证n小于等于300,矩阵中的元素为int范围内。</int></vector></int></vector>
测试样例:
[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]
刚开始想一个一个遍历,然后某一个位置为0,就把对应的行和列变为0,后来想想不对
网上查了下,发现这会导致数组中有一个为0,对应的行和列也变为0,这样导致整个
数组都变为0了
下面思路是把为0的行号和列号记录下来,
然后根据记录下来的信息,对整个数组进行遍历即可
class Clearer {
public:
vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
// write code here
vector<bool> row(n, 0), col(n, 0);
for(int i = 0; i < n; i++)
{
for(int j = 0; j < n; j++)
{
if(mat[i][j] == 0)
{
row[i] = true;
col[j] = true;
}
}
}
for(int i = 0; i < n; ++i)
{
for(int j = 0; j < n; ++j)
{
if(row[i] || col[j])
{
mat[i][j] = 0;
}
}
}
return mat;
}
};
清除数列
最新推荐文章于 2023-08-09 18:46:38 发布