稀疏数组是一种数据结构,可以节省存储空间
稀疏数组和二维数组的关系图:
以棋盘为例,代码实现:
package com.company;
public class Main {
public static void main(String[] args) {
//原始的二维数组
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
System.out.println("原始二维数组:");
for (int[] row : chessArr1) {
for (int value : row) {
System.out.print(value + "\t");
}
System.out.println();
}
//获取原始二维数组中一共有几个数据
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0) {
sum++;
}
}
}
//对应的稀疏数组sparseArr
int[][] sparseArr = new int[sum + 1][3];
sparseArr[0][0] = 11;
sparseArr[0][1] = 11;
sparseArr[0][2] = sum;
//count作为计数指向稀疏数组的行
int count = 0;
//给稀疏数组赋值
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < 11; j++) {
if (chessArr1[i][j] != 0) {
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
System.out.println("打印对应的稀疏数组:");
for (int i = 0; i < sparseArr.length; i++) {
for (int j = 0; j < 3; j++) {
System.out.print(sparseArr[i][j] + "\t");
}
System.out.println();
}
//定义一个新二维数组作为还原后的二维数组
int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("还原对应的二维数组:");
for (int[] row : chessArr2) {
for (int value : row) {
System.out.print(value + "\t");
}
System.out.println();
}
}
}
执行效果如下: