整个代码放在main函数中就可以运行
从数组---->稀疏数组
int arrays[][] = new int[11][11];
arrays[1][2] = 1;
arrays[2][3] = 2;
//打印初始化的数组
for (int i = 0;i<arrays.length;i++){
for (int j = 0;j<arrays[i].length;j++){
System.out.print(arrays[i][j]);
}
System.out.println();
}
int sum = 0;
for (int i = 0;i<arrays.length;i++){
for (int j = 0;j<arrays[i].length;j++){
if(arrays[i][j] != 0)
sum++;
}
}
//得到稀疏数组
int array[][] = new int[sum+1][3];
array[0][0] = arrays.length;
array[0][1] = arrays[0].length;
array[0][2] = sum;
int k=1;
for (int i = 0;i<arrays.length;i++){
for (int j = 0;j<arrays[i].length;j++){
if(arrays[i][j] != 0) {
array[k][0] = i;
array[k][1] = j;
array[k][2] = arrays[i][j];
k++;
}
}
}
//打印稀疏数组
System.out.println("打印稀疏数组");
for (int i = 0;i<array.length;i++){
for (int j = 0;j<array[i].length;j++){
System.out.print(array[i][j]+"\t");
}
System.out.println();
}
从稀疏数组----->原数组
//由稀疏数组恢复原数组
int rows = array[0][0];
int column = array[0][1];
int arryRecovery[][] = new int[rows][column];
for (int i = 1; i < array.length; i++) {
arryRecovery[array[i][0]][array[i][1]] = array[i][2];
}
//打印恢复的数组
System.out.println("打印恢复的数组");
for (int i = 0;i<arryRecovery.length;i++){
for (int j = 0;j<arryRecovery[i].length;j++){
System.out.print(arryRecovery[i][j]);
}
System.out.println();
}
|