- 当一个数组中大部分元素都是0,或者为同一值的数组时,可以使用稀疏数组来保存该数组。
- 稀疏数组的处理方式是:
- 记录数组一共有几行几列,有多少个不同值
- 把具有不同值的元素和行列及值记录在一个小规模的数组中,从而缩小程序的规模
public class ArrayDemo1 {
public static void main(String[] args) {
//创建一个11*11的棋盘。0:没有棋子;1:黑棋;2,白棋;
int[][] a = new int[11][11];
a[1][2]=1;
a[2][3]=2;
//输出原始数组
System.out.println("输出原始数组:");
for (int[] ints:a) {
for (int anint : ints) {
System.out.print(anint + "\t");
}
System.out.println();
}
//转换为稀疏数组
//获取有效值个数
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (a[i][j] != 0) {
sum ++;
}
}
}
System.out.println("有效值个数:" + sum);
//创建一个稀疏数组
int[][] b = new int[sum+1][3];
b[0][0] = 11;
b[0][1] = 11;
b[0][2] = sum;
//遍历二维数组,将非零的值,存放到稀疏数组中
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int j = 0; j < a[i].length; j++) {
if (a[i][j] != 0) {
count ++;
b[count][0] = i;
b[count][1] = j;
b[count][2] = a[i][j];
}
}
}
//输出稀疏数组
System.out.println("输出稀疏数组:");
for (int i = 0; i < b.length; i++) {
System.out.println(b[i][0] + "\t"
+ b[i][1] + "\t"
+ b[i][2] + "\t");
}
//稀疏数组还原
System.out.println("还原:");
//读取稀疏数组
int[][] c = new int[b[0][0]][b[0][1]];
//给其中的元素还原值
for (int i = 1; i < b.length; i++) {
c[b[i][0]][b[i][1]] = b[i][2];
}
//打印还原数组:
System.out.println("输出还原数组:");
for (int[] ints:c) {
for (int anint : ints) {
System.out.print(anint + "\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
标签:11,59,数组,int,System,稀疏,秦疆,out
From: https://www.cnblogs.com/Acolyte/p/17877437.html