1 package com.pingfan.array;
2
3 import sun.security.util.Length;
4
5 public class ArrayDemo8 {
6 public static void main(String[] args) {
7 //1.创建一个二维数组 11*11 0:没有棋子,1:黑棋,2:白棋
8 int[][] array1 = new int[11][11];
9 array1[1][2] = 1;
10 array1[2][3] = 2;
11 //输出原始的数组
12 System.out.println("输出原始的数组");
13 for (int[] ints : array1) {
14 for (int anInt : ints) {
15 System.out.print(anInt+"\t");
16 }
17 System.out.println();
18 }
19 System.out.println("==================");
20 //转换为稀疏数组保存
21 //获取有效值的个数
22 int sum = 0;
23 for (int i = 0; i < 11; i++) {
24 for (int j = 0; j < 11; j++) {
25 if (array1[i][j]!=0){
26 sum++;
27 }
28 }
29 }
30 System.out.println("有效值的个数"+sum);
31 //2.创建一个稀疏数组的数组
32 int[][] array2 = new int[sum + 1][3];
33 array2[0][0] = 11;
34 array2[0][1] = 11;
35 array2[0][2] = sum;
36 //遍历二维数组,将非零的值,存放稀疏数组中
37 int count = 0;
38 for (int i = 0; i < array1.length; i++) {
39 for (int j = 0; j < array1[i].length; j++) {
40 if (array1[i][j]!=0){
41 count++;
42 array2[count][0] = i;
43 array2[count][1] = j;
44 array2[count][2] = array1[i][j];
45 }
46 }
47 }
48 //输出稀疏数组
49 System.out.println("稀疏数组");
50 for (int i = 0; i < array2.length; i++) {
51 System.out.println(array2[i][0]+"\t"+
52 array2[i][1]+"\t"+
53 array2[i][2]+"\t");
54 }
55 System.out.println("==================");
56 System.out.println("还原");
57 //1.读取稀疏数组
58 int[][] array3 = new int[array2[0][0]][array2[0][1]];
59 //2.给其中的元素还原它的值
60 for (int i = 1; i < array2.length; i++) {
61 array3[array2[i][0]][array2[i][1]] = array2[i][2];
62 }
63 //3.打印
64 System.out.println("输出还原的数组");
65 for (int[] ints : array3) {
66 for (int anInt : ints) {
67 System.out.print(anInt+"\t");
68 }
69 }
70 }
71 }