2023.7.20 周四:稀疏数组
1 import java.sql.SQLOutput; 2 import java.util.Arrays; 3 import java.util.Scanner; 4 //稀疏数组 5 public class test { 6 public static void main(String[] args) { 7 //首先创建一个11*11的二维数组 0:没有棋子 1:白棋 2:黑棋 8 int[][] array1 = new int[11][11]; 9 array1[1][2] = 1; 10 array1[2][3] = 2; 11 System.out.println("输出原始的数组"); 12 for (int[] ints : array1) { 13 for (int anInt : ints) { 14 System.out.print(anInt+"\t "); 15 } 16 System.out.println(); 17 } 18 System.out.println("=========================================="); 19 //转换为稀疏数组保存 20 int sum = 0;//获取有效值的个数 21 for (int i = 0; i < 11; i++) { 22 for (int j = 0; j < 11; j++) { 23 if(array1[i][j] != 0){ 24 sum++; 25 } 26 } 27 } 28 System.out.println("有效值的个数 = "+sum); 29 int array2[][] = new int[sum+1][3]; 30 array2[0][0] = 11; 31 array2[0][1] = 11; 32 array2[0][2] = sum; 33 //遍历二维数组,将不是零的值,赋给稀疏数组 34 int count = 0; 35 for (int i = 0; i < array1.length; i++) { 36 for (int j = 0; j < array1[i].length; j++) { 37 if(array1[i][j] != 0){ 38 count++; 39 array2[count][0] = i; 40 array2[count][1] = j; 41 array2[count][2] = array1[i][j]; 42 } 43 } 44 } 45 System.out.println("输出稀疏数组"); 46 for (int i = 0; i < array2.length; i++) { 47 System.out.println(array2[i][0]+"\t" 48 +array2[i][1]+"\t" 49 +array2[i][2]); 50 } 51 System.out.println("============================="); 52 System.out.println("还原"); 53 int[][] array3 = new int[array2[0][0]][array2[0][1]]; 54 for (int i = 1; i < array2.length; i++) { 55 array3[array2[i][0]][array2[i][1]] = array2[i][2]; 56 } 57 for (int[] ints : array3) { 58 for (int anInt : ints) { 59 System.out.print(anInt+"\t "); 60 } 61 System.out.println(); 62 } 63 } 64 }