1 public class SpareArray {
2 public static void main(String[] args) {
3 /**
4 * 创建原始的二维数组:11 * 11
5 * 0:表示没有棋子
6 * 1:表示黑子
7 * 2:表示蓝子
8 */
9 int chessArray[][] = new int[11][11];
10 chessArray[1][2] = 1;
11 chessArray[2][4] = 2;
12 chessArray[5][4] = 2;
13 //遍历原始数组
14 int sum = 0;
15 for(int[] row : chessArray) {
16 for(int data : row) {
17 if(data != 0) {
18 sum++;
19 }
20 System.out.printf("%d\t",data);
21 }
22 System.out.println();
23 }
24 //得到有效数字的个数sum
25 System.out.println("有效数字个数:" + sum);
26 //1、根据有效数字个数创建spareArray稀疏数组
27 int[][] spareArray = new int[sum+1][3];
28 //2、为系数数组赋值【第一行】
29 spareArray[0][0] = chessArray.length;
30 spareArray[0][1] = chessArray.length;
31 spareArray[0][2] = 3;
32 //遍历原始数组:为稀疏数组其余位置赋值
33 int count = 0;
34 for(int i = 0; i < chessArray.length; i++) {
35 for(int j = 0; j < chessArray.length; j++) {
36 if(chessArray[i][j] != 0) {
37 count++;
38 spareArray[count][0] = i; //稀疏数组的行
39 spareArray[count][1] = j; //列
40 spareArray[count][2] = chessArray[i][j]; //值
41 }
42 }
43 }
44 //输出稀疏数组
45 System.out.println("输出稀疏数组:");
46 for(int i = 0; i < sum + 1; i++) {
47 for(int j = 0; j < 3; j++) {
48 System.out.printf("%d\t",spareArray[i][j]);
49 }
50 System.out.println();
51 }
52
53 //将稀疏数组还原成原始数组
54 //1、根据稀疏数组第一行的值创建一个与原始数组大小一样的二维数组
55 int[][] chessArray2 = new int[spareArray[0][0]][spareArray[0][1]];
56 //2、按照行来还原数据【每行通过行和列以及数值可以确定一个数据】
57 for(int i = 1; i < sum+1; i++) {
58 for(int j = 0; j < 3; j++) {
59 chessArray2[spareArray[i][0]][spareArray[i][1]] = spareArray[i][2];
60 }
61 }
62 //输出还原后的数组
63 System.out.println("还原后的二维数组:");
64 for(int[] row : chessArray2) {
65 for(int data : row) {
66 System.out.printf("%d\t",data);
67 }
68 System.out.println();
69 }
70 }
71 }
![]()