请编写一个算法,若N阶方阵中某个元素为0,则将其所在的行与列清零。
给定一个N阶方阵int[][](C++中为vector<vector>)mat和矩阵的阶数n,请返回完成操作后的int[][]方阵(C++中为vector<vector>),保证n小于等于300,矩阵中的元素为int范围内。</vector</vector
测试样例:
[[1,2,3],[0,1,2],[0,0,1]]
返回:[[0,0,3],[0,0,0],[0,0,0]]
import java.util.*;
public class Clearer {
public int[][] clearZero(int[][] mat, int n) {
// write code here
int row,col;
boolean[] zRow=new boolean[300];
boolean[] zCol=new boolean[300];
boolean flagR,flagC;
for (row=0;row<n;row++)
for(col=0;col<n;col++)
if(mat[row][col]==0)
{
zRow[row]=true;//一开始想用数组存值为0的矩阵元素坐标的,看到另一个大兄弟的算法就跟着改了,简单很多
zCol[col]=true;
}
for(row=0;row<n;row++)
for(col=0;col<n;col++)
if(zRow[row]|| zCol[col])
{
mat[row][col]=0;
}
return mat;
}
}