扩展:稀疏数组-数据结构

 

 

 

 

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

 

posted @ 2021-02-17 00:54  奔啵儿灞  阅读(54)  评论(0)    收藏  举报