public class test11 {
public static void main(String[] args) {
// TODO Auto-generated method stub
int[][] arrys = new int[11][11];
arrys[1][2] = 1 ;
arrys[2][3] = 1 ;
System.out.println("输出原始数组:");
for (int[] is : arrys) {
for (int is2 : is) {
System.out.print(is2 + " ");
}
System.out.println();
}
System.out.println("-------------------------------");
//转换为稀疏数组并保存
//获取有效值的个数
int sum = 0;
for (int[] is : arrys) {
for (int is2 : is) {
if(is2 != 0) {
sum++;
}
}
}
System.out.println("有效值的个数为:" + sum);
//2.创建一个稀疏数组
int[][] arry2 = new int[sum+1][3];
int count = 0;
arry2[0][0] = 11;
arry2[0][1] = 11;
arry2[0][2] = sum;
//遍历数组,寻找非零的数并存入arry2
for (int i = 0; i < arrys.length; i++) {
for (int j = 0; j < arrys[i].length; j++) {
if(arrys[i][j] != 0) {
count++;
arry2[count][0] = i;
arry2[count][1] = j;
arry2[count][2] = arrys[i][j];
}
}
}
System.out.println("输出稀疏数组:");
//输出稀疏数组
for (int i = 0; i < arry2.length; i++) {
System.out.println(arry2[i][0] + "\t" + arry2[i][1]+ "\t" + arry2[i][2]);
}
System.out.println("-------------------------------");
System.out.println("由稀疏数组再转换成普通数组:");
//1.读取稀疏数组
int[][] arry3 = new int[arry2[0][0]][arry2[0][1]];
//2.给其中的元素还原他的值
for (int i = 1; i < arry2.length; i++) {
arry3[arry2[i][0]][arry2[i][1]] = arry2[i][2];
}
System.out.println("-------------------------------");
System.out.println("输出原始数组:");
for (int[] is : arry3) {
for (int is2 : is) {
System.out.print(is2 + " ");
}
System.out.println();
}
}
}
控制台:
输出原始数组:
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 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
有效值的个数为:2
输出稀疏数组:
行 列 数值
11 11 2
1 2 1
2 3 1
由稀疏数组再转换成普通数组:
输出原始数组:
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 1 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0