稀疏数组
- 当一个数组中大部分元素为0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
- 稀疏数组的处理方式是:
- 记录数组一共有几行几列,有多少不同值
- 把具体有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
package com.cnblogs;
public class Demo {
public static void main(String[] args) {
//创建一个二维数组11*11 0:没有旗子 1:黑子 2:白子
int[][] arr = new int[11][11];
arr[1][2] = 1;
arr[2][3] = 2;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[i].length; j++) {
System.out.print(arr[i][j]+ "\t");
}
System.out.println();
}
System.out.println("===========================================");
//转换为稀疏数组保存
//1.获取有效值的个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(arr[i][j]!=0){
sum++;
}
}
}
System.out.println("输出有效值的个数为:"+sum);
//2.创建一个稀疏数组的数组
int[][] arrs = new int[sum+1][3];
arrs[0][0] =11;
arrs[0][1] =11;
arrs[0][2] =sum;
//3.遍历二维数组,将非零的值,存放稀疏数组中
int count = 0;
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < arr[1].length; j++) {
if(arr[i][j]!=0){
count++;
arrs[count][0] = i;
arrs[count][1] = j;
arrs[count][2] = arr[i][j];
}
}
}
//输出稀疏数组
for (int i = 0; i < arrs.length; i++) {
for (int j = 0; j < arrs[i].length; j++) {
System.out.print(arrs[i][j]+ "\t");
}
System.out.println();
}
System.out.println("===========================================");
System.out.println("还原稀疏数组:");
//1.读取稀疏数组
int[][] array = new int[arrs[0][0]][arrs[0][1]];
//2.给其中的元素还原他的值
for (int i = 1; i < arrs.length; i++) {
array[arrs[i][0]][arrs[i][1]] = arrs[i][2];
}
//打印还原数组
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
System.out.print(array[i][j]+ "\t");
}
System.out.println();
}
}
}
所有打印结果如下:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
===========================================
输出有效值的个数为:2
11 11 2
1 2 1
2 3 2
===========================================
还原稀疏数组:
0 0 0 0 0 0 0 0 0 0 0
0 0 1 0 0 0 0 0 0 0 0
0 0 0 2 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0