【蓝桥杯】 将0所在的行和列全置为0

题目描述

1 2 3 4
5 6 0 8
9 0 11 12
13 14 15 16

 

 

 

 

 

结果输出:

1 0 0 4
0 0 0 0
0 0 0 0
13 0 0 16

 

 

 

 

 

分析:设置辅助数组记录出现0的行和列。

接下来遍历原数组,将辅助数组中等于1 的row和col记做0。

 1 public class case2 {
 2 
 3     public static void main(String[] args) {
 4 
 5         int arr[][] = {
 6                 { 1, 2, 3, 4 },
 7                 { 5, 6,0, 8 }, 
 8                 { 9, 0, 11, 12 },
 9                 { 13, 14, 15, 16 }
10           };
11         solve(arr);
12         printMatrix(arr);
13     
14     }
15     static void solve(int [][]matrix){
16         int M=matrix.length;
17         int N=matrix[0].length;
18         int []rowRecord=new int [M];
19         int []colRecord=new int [N];
20         for(int i=0;i<M;i++){
21             for(int j=0;j<N;j++){
22                 if(matrix[i][j]==0){
23                     rowRecord[i]=1;
24                     colRecord[j]=1;
25                 }
26             }
27         }
28         
29         for(int row=0;row<M;row++){
30             for(int col=0;col<N;col++){
31                 if(rowRecord[row]==1 || colRecord[col]==1){
32                     matrix[row][col]=0;
33                 }
34             }
35         }
36         
37     }
38 //二维数组(矩阵)的打印
39     public static void printMatrix(int [][]marix){
40         for(int []arr:marix){
41             for(int e:arr){
42             //    if(e!=0)//只打印不包含0的行和列
43                 System.out.print(e+"\t");
44             }
45             System.out.println();
46         }
47         
48     }
49 
50 }

ps:如果将包含0的行或列不打印,只需要在打印函数中添加条件if(e!=0)即可。

持续更新中……

 

posted on 2020-07-21 18:33  丁不煮  阅读(281)  评论(0)    收藏  举报

导航