1 package com.xgp.数据结构.非线性结构.稀疏数组.Demo1;
 2
 3 /**
 4  * 稀疏数组------>棋盘存盘问题
 5  */
 6 public class SparseArray {
 7     public static void main(String[] args) {
 8         //创建一个原始的二维数组 11*11
 9         //0:无 1:黑 2:蓝 色棋子
10         int[][] chessArray1 = new int[11][11];
11         chessArray1[1][2] = 1;
12         chessArray1[2][3] = 2;
13         System.out.println("原始的二维数组:");
14         for (int[] row : chessArray1) {
15             for (int data : row) {
16                 System.out.print(data + "\t");
17             }
18             System.out.println();
19         }
20
21         //将二维数组转稀疏数组
22         //1,先遍历二维数组,等到非0数据的个数
23         int sum = 0;
24         for (int[] ints : chessArray1) {
25             for (int anInt : ints) {
26                 if(anInt != 0) {
27                     sum++;
28                 }
29             }
30         }
31 //        System.out.println("sum = " + sum);
32         //2,创建对应的稀疏数组
33         int[][] sparseArray = new int[sum+1][3];
34         //给稀疏数组赋值
35         sparseArray[0][0] = 11;
36         sparseArray[0][1] = 11;
37         sparseArray[0][2] = sum;
38         //遍历二维数组,将非0的值存到稀疏数组中
39         int count = 0;  //用于记录是第几个非0数据
40         for (int i = 0;i < 11 ;i++) {
41             for (int j = 0; j < 11;j++) {
42                 if(chessArray1[i][j] != 0) {
43                     count++;
44                     sparseArray[count][0] = i;
45                     sparseArray[count][1] = j;
46                     sparseArray[count][2] = chessArray1[i][j];
47                 }
48             }
49         }
50
51         //输录稀疏数组
52         System.out.println("得到的稀疏数组为:");
53         System.out.println("行数\t列数\t值");
54         for (int[] ints : sparseArray) {
55             for (int anInt : ints) {
56                 System.out.print(anInt + "\t\t");
57             }
58             System.out.println();
59         }
60
61         //将稀疏数组恢复成二维数组
62         //1,先读取稀疏数组的第一行,根据第一数据,创建原始的二维数组
63         int[][] chessArray2 = new int[sparseArray[0][0]][sparseArray[0][1]];
64         //给恢复的二维数组赋值
65         for(int i = 1;i < sparseArray.length;i++) {
66             chessArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
67         }
68
69         System.out.println("恢复后的二维数组:");
70         for (int[] ints : chessArray2) {
71             for (int anInt : ints) {
72                 System.out.print(anInt + "\t");
73             }
74             System.out.println();
75         }
76     }
77 }
02-12 05:10