https://blog.csdn.net/baolingye/article/details/99943083
package com.chen.Two;
/**
* @author Chen
* @date 2023年12月14日 11:05
*/
public class SparseArray {
public static void main(String[] args) {
int[][] array1 = new int[11][11]; //起始数组
array1[1][2] = 1;
array1[2][3] = 2;
for (int[] ints : array1) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
int sum = 0; //计算数组中的有效数
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j <array1.length; j++) {
if (array1[i][j]!=0){
sum++;
}
}
}
System.out.println("有效个数为:"+sum);
int[][] array2 = new int[sum+1][3]; //稀疏数组
array2[0][0] = array1.length;
array2[0][1] = array1.length;
array2[0][2] = sum;
for (int i = 0; i < array1.length; i++) {
for (int j = 0; j < array1.length; j++) {
if (array1[i][j]!=0){
array2[i][0] = i;
array2[i][1] = j;
array2[i][2] = array1[i][j];
}
}
}
for (int i = 0; i < array2.length; i++) {
for (int j = 0; j < array2.length; j++) {
System.out.print(array2[i][j]+"\t");
}
System.out.println();
}
//还原稀疏数组
int[][] array3 = new int[array2[0][0]][array2[0][1]];
for (int i = 1; i < array2.length; i++) {
array3[array2[i][0]][array2[i][1]] = array2[i][2];
}
for (int[] ints : array3) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}
标签:11,数组,int,array1,稀疏,ints,out
From: https://www.cnblogs.com/qwer12138/p/17901057.html