int[][] array = new int[11][11]
array[1][2] = 1;
array[2][3] = 2;
for (int[] arra: array) {
for (int arra2:arra) {
System.out.print(arra2+"\t");
}
System.out.println();
}
int sum = 0;
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if (array[i][j] != 0) {
sum++;
}
}
}
int[][] array2 = new int[sum+1][3];
array2[0][0] = 11;
array2[0][1] = 11;
array2[0][2] = sum;
int count = 0;
for (int i = 0; i <array.length; i++){
for(int j = 0; j<array[i].length;j++){
if(array[i][j] != 0){
count ++
array2[count][0] = i;
array2[count][1] = j;
array2[count][2] = array[i][j];
}
}
}
输出原始数组:
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 0
输出稀疏数组:
11 11 2
1 2 1
2 3 2
int[][] array2 = new int[array1[0][0]][array1[0][1]];
for (int i = 1;i < array1.length ; i++){
array2[array1[i][0]][array1[i][1]] = array1[i][2];
}
输出还原数组:
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 0