public class array {
/*
* @auther: YangWanFa
* @effect: learn Sparse array
*
* */
public static void main(String[] args) {
int [] [] array01 = new int[11][11];
array01[1][2] = 1;
array01[2][3] = 2;
//输出原始数组
/*for (int i = 0; i < array01.length; i++) {
for (int j = 0; j < array01.length; j++) {
System.out.print(array01[i][j]+" ");
}
System.out.println("");
}*/
for (int[] ints : array01) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println("");
}
System.out.println("=============================");
int sum = 0;
//取出稀疏数组内有效值的个数
for (int i = 0; i < array01.length; i++) {
for (int i1 = 0; i1 < array01.length; i1++) {
if(array01[i][i1] != 0){
sum++;
}
}
}
System.out.println("有效值的个数:"+sum);
//创建一个稀疏数组的对应数组
int[][] arraySparesArray = new int[sum+1][3];
arraySparesArray[0][0] = array01.length;//存放数组的行数
arraySparesArray[0][1] = array01[0].length;//存放数组的列数
arraySparesArray[0][2] = sum;//array [0][2] put is value
int temp = 1;
//遍历二维数组 将非0值存放至稀疏数组内
for (int i = 0; i < array01.length; i++) {
for (int j = 0; j < array01[i].length; j++) {
if(array01[i][j] != 0){
arraySparesArray[temp][0] = i;
arraySparesArray[temp][1] = j;
arraySparesArray[temp][2] = array01[i][j];
temp++;
}
}
}
System.out.println("输出稀疏数组:");
//输出稀疏数组
for (int i = 0; i < arraySparesArray.length; i++) {
/*for (int j = 0; j < arraySparesArray[i].length; j++) {
System.out.print(arraySparesArray[i][j]+" ");
}
System.out.println(" ");*/
System.out.println(arraySparesArray[i][0]+"\t"+ arraySparesArray[i][1]+"\t"+arraySparesArray[i][2]);
}
//readSparesArray
//还原稀疏数组所表示的表格
int arrayread[][] = new int[arraySparesArray[0][0]][arraySparesArray[0][1]];
//还原稀疏数组所表示的表格
for (int i = 1; i < arraySparesArray.length; i++) {
arrayread[arraySparesArray[i][0]][arraySparesArray[i][1]] = arraySparesArray[i][2];
}
//打印
for (int[] ints : arrayread) {
for (int anInt : ints) {
System.out.print(anInt+" ");
}
System.out.println("");
}
}
}