效果展示
代码
package com.atguigu.sparsearray;
public class SparseArray {
public static void main(String[] args) {
// 手动创建一个稀疏的二维数组,为了后面使用
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
// 遍历数组,打印元素
for (int[] row: chessArr1
) {
for (int col:row
) {
System.out.printf("%d\t",col);
}
System.out.println();
}
// 根据稀疏数组,创建小数组
// 1.首先,遍历稀疏数组,找到所有非零的数,并计数
int sum = 0;
for (int[] row: chessArr1
) {
for (int col:row
) {
if(col != 0){
sum++;
}
}
}
int[][] sparseArr = new int[sum+1][3];
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1.length;
sparseArr[0][2] = sum;
int count = 0;
for(int i = 0; i < chessArr1.length; i++){
for(int j = 0; j < chessArr1.length; j++){
if(chessArr1[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
// 稀疏数组
for (int i = 0; i < sparseArr.length; i++){
System.out.printf("%d\t%d\t%d\t",sparseArr[i][0], sparseArr[i][1], sparseArr[i][2]);
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];
}
// 打印还原的数组
for (int[] row: chessArr2
) {
for (int col: row
) {
System.out.printf("%d\t",col);
}
System.out.println();
}
}
}