package com.dhu.sparsearray;public class SparseArrsy {public static void main(String[] args) {int chessArr1[][] = new int[11][11];chessArr1[1][2] = 1;chessArr1[2][3] = 2;chessArr1[3][4] = 11;System.out.printf("原始二维数组");for (int[] row : chessArr1){for (int data : row){System.out.printf("%d\t", data);}System.out.println();}//1. 遍历二维数组,找到非零个数int sum = 0;for (int i = 0; i < chessArr1.length; i++){for (int j = 0; j < chessArr1.length; j++){if(chessArr1[i][j] != 0){sum++;}}}//System.out.println(sum);//2.创建对应稀疏数组int sparseArr[][] = new int[sum + 1][3];sparseArr[0][0] = 11;sparseArr[0][1] = 11;sparseArr[0][2] = sum;//遍历二维数组,将非0值存放到sparseArrint 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];}}}// 输出稀疏数组System.out.println();System.out.println("得到的稀疏数组为如下形式");for (int i = 0; i < sparseArr.length; i++){System.out.printf("%d\t%d\t%d\t\n", 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];}System.out.println();System.out.println("恢复后的二维数组");for (int[] row : chessArr2){for (int data : row){System.out.printf("%d\t", data);}System.out.println();}}
}