清除行列

题目描述

请编写一个算法,若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]]

 1 import java.util.*;
 2 
 3 public class Clearer {
 4     public int[][] clearZero(int[][] mat, int n) {
 5         // write code here
 6         boolean[] row = new boolean[mat.length];
 7         boolean[] column = new boolean[mat[0].length];
 8         for(int i = 0 ;i < mat.length;++i)
 9         {
10             for(int j = 0 ;j < mat[0].length;++j)
11             {
12                 if(mat[i][j] == 0)
13                 {
14                     row[i] = column[j] = true;
15                 }
16             }
17         }
18         
19         for(int i = 0 ;i < mat.length;++i)
20         {
21             for(int j = 0 ;j < mat[0].length;++j)
22             {
23                 if(mat[i][j] !=0 && (row[i] || column[j])) mat[i][j] = 0;
24             }
25         }
26         return mat;
27     }
28 }

 

posted @ 2016-03-29 16:47  小爷  阅读(214)  评论(0编辑  收藏  举报