package 数组.稀疏数组;
public class 稀疏数组 {
public static void main(String[] args) {
int arr[][] = new int[11][11];
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
arr[1][2] = 9;
arr[2][3] = 5;
}
}
int[][] res = change(arr);
System.out.println("转为稀疏数组");
printArr(res);
System.out.println("再将稀疏数组转为棋盘");
int[][] a = restore(res);
printArr(a);
}
public static int[][] change(int[][] arr){
int sum = 0;
for (int[] ints : arr) {
for (int num : ints) {
if (num != 0) {
sum++;
}
System.out.print(num + "\t");
}
System.out.println();
}
int count = 0;
int res[][] = new int[sum + 1][3];
res[0][0] = arr.length;
res[0][1] = arr[0].length;
res[0][2] = sum;
for (int i = 0; i < arr[0].length; i++) {
for (int j = 0; j < arr[0].length; j++) {
if (arr[i][j] != 0) {
count++;
res[count][0] = i;
res[count][1] = j;
res[count][2] = arr[i][j];
}
}
}
return res;
}
public static int[][] restore(int[][] res){
int a[][] = new int[res[0][0]][res[0][1]];
int c = 0;
for (int i = 0; i < res[0][2]; i++) {
c++;
a[res[c][0]][res[c][1]] = res[c][2];
}
return a;
}
public static void printArr(int[][] arr){
for (int[] ints : arr) {
for (int num : ints) {
System.out.print(num+"\t");
}
System.out.println();
}
}
}