1. 程式人生 > 實用技巧 >【藍橋杯】 將0所在的行和列全置為0

【藍橋杯】 將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)即可。

持續更新中……