您的位置:首页 > 其它

清除行列

2016-03-29 16:47 381 查看

题目描述

请编写一个算法,若MxN矩阵中某个元素为0,则将其所在的行与列清零。

给定一个MxN的int[][]矩阵mat和矩阵的阶数n,请返回完成操作后的int[][]矩阵,保证n小于等于300,矩阵中的元素为int范围内。

测试样例:
[[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
boolean[] row = new boolean[mat.length];
boolean[] column = new boolean[mat[0].length];
for(int i = 0 ;i < mat.length;++i)
{
for(int j = 0 ;j < mat[0].length;++j)
{
if(mat[i][j] == 0)
{
row[i] = column[j] = true;
}
}
}

for(int i = 0 ;i < mat.length;++i)
{
for(int j = 0 ;j < mat[0].length;++j)
{
if(mat[i][j] !=0 && (row[i] || column[j])) mat[i][j] = 0;
}
}
return mat;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: