package com.example.datastructures.sparsearray;
/**
* @author maoyouhua
* @version jdk21
* 稀疏数组
* 经典场景: 五子棋存档问题
* 好处:摒弃大量无用数据,能够减少存储空间的使用
* 以下例子:
* 存储空间: 11 * 11 -> 3 * 3
*/
public class SparseArray {
public static void main(String[] args) {
// 0表示没有棋子 1表示黑子 2 表示白子
int[][] chessArr1 = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][3] = 2;
chessArr1[7][4] = 2;
System.out.println("遍历普通二维数组");
traversalArray(chessArr1);
int[][] sparseArray = commonToSparse(chessArr1);
System.out.println("遍历稀疏数组");
traversalArray(sparseArray);
int[][] commonArray = sparseToCommon(sparseArray);
System.out.println("遍历稀疏数组转化的二维数组");
traversalArray(commonArray);
}
/**
* 打印二维数组数据
*/
private static void traversalArray(int[][] arr){
for (int[] row : arr) {
for (int data : row) {
System.out.printf("%d\t",data);
}
System.out.println("\t");
}
}
/**
* 普通二维数组转化为稀疏数组
*/
private static int[][] commonToSparse(int[][] commonArray){
int sum = 0;
int count = 1;
int row = commonArray.length;
int column = commonArray[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if(commonArray[i][j] != 0){
sum++;
}
}
}
int[][] sparseArray = new int[sum + 1][3];
sparseArray[0][0] = row;
sparseArray[0][1] = column;
sparseArray[0][2] = sum;
for (int i = 0; i < row; i++) {
for (int j = 0; j < column; j++) {
if(commonArray[i][j] != 0){
sparseArray[count][0] = i;
sparseArray[count][1] = j;
sparseArray[count][2] = commonArray[i][j];
count++;
}
}
}
return sparseArray;
}
/**
* 稀疏数组转化为普通二维数组
*/
private static int[][] sparseToCommon(int[][] sparseArray){
int[][] commonArray = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1; i < sparseArray.length; i++) {
commonArray[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
return commonArray;
}
}