题目描述
请编写一个算法,若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]]
Solution 1(常规思路)
//常规思路,就是找出所有为0的位置,再将对应的行列分别置0,中间需要一个标志
class Clearer {
public:
vector<vector<int> > clearZero(vector<vector<int> > mat, int n) {
if(n<=0) return mat;
int state[n][n];
memset(state,0,sizeof state);
queue<pair<int,int>>q;
for(int i=0;i<mat.size();++i)
for(int j=0;j<mat[i].size();++j)
if(mat[i][j]==0)
q.push(pair<int,int>(i,j));
while(!q.empty())
{
pair<int,int>front=q.front();
q.pop();
state[front.first][front.second]=1;
for(int k=0;k<n;++k)
if(mat[k][front.second]!=0&&state[k][front.second]==0)
{
mat[k][front.second]=0;
state[k][front.second]=1;
}
for(int k=0;k<n;++k)
if(mat[front.first][k]!=0&&state[front.first][k]==0)
{
mat[front.first][k]=0;
state[front.first][k]=1;
}
}
return mat;
}
};
Solution 2(行列分开考虑)
publicclassClearer {
publicint[][] clearZero(int[][] mat, intn) {
// write code here
boolean[] rowArray = newboolean[n];
boolean[] columnArray = newboolean[n];
//记录为0的位置,把相应的行列位置设为true
for(int i=0; i<n;i++)
{
for(intj=0;j<n;j++)
{
if(mat[i][j]==0)
{
rowArray[i]=true;
columnArray[j]=true;
}
}
}
//遍历找到之前记录的位置,把相应行列赋值为0
for(int i=0;i<n;i++)
{
for(intj=0;j<n;j++)
{
if(rowArray[i]||columnArray[j])
{
mat[i][j] = 0;
}
}
}
returnmat;
}
};