public class sparseArray { public static void main(String[] args) { int[][] array = new int[11][11]; array[1][3] = 1; array[2][4] = 2; for (int[] i:array) { for (int i1:i){ System.out.print(i1+"\t"); } System.out.println(); } //稀疏数组 System.out.println("================================="); //计算非零数的个数 int sum = 0; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] != 0){ sum++; } } } int[][] array1 = new int[sum+1][3]; array1[0][0] = 11; array1[0][1] = 11; array1[0][2] = sum; //非零赋值 int count = 1; for (int i = 0; i < array.length; i++) { for (int j = 0; j < array[i].length; j++) { if (array[i][j] != 0){ array1[count][0] = i; //把行的位置赋值 array1[count][1] = j; //把列的位置赋值 array1[count][2] = array[i][j]; //数值赋值 count++; } } } //打印输出 System.out.println("稀疏数组"); for (int i = 0; i < array1.length; i++) { System.out.println(array1[i][0]+"\t"+ array1[i][1]+"\t"+array1[i][2]); } //稀疏数组还原 int[][] array2 = new int[array1[0][0]][array1[0][1]]; for (int i = 1; i < array1.length; i++) { //i要从1开始,不能从0,会下标越界,因为索引是从0到10,读取11会越界 array2[array1[i][0]][array1[i][1]] = array1[i][2]; } for (int[] i:array2) { for (int i1:i){ System.out.print(i1+"\t"); } System.out.println(); } } }
输出结果:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 ================================= 稀疏数组 11 11 2 1 3 1 2 4 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 0 0 0 0 2 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
稀疏数组例子如图: