主函数
public static void main(String[] args) {
int [][] array1=new int[11][11];
array1[1][2]=1;
array1[2][3]=2;
array1[1][3]=1;
array1[2][4]=2;
System.out.println("原型");
arrays(array1);
int[][] array2 = arraysX(array1);
System.out.println("处理后的稀疏数组");
arrays(array2);
System.out.println("还原");
int[][] array3 = arraysH(array2);
arrays(array3);
}
生成稀疏数组
public static int[][] arraysX(int[][] array)
{
int number=0;
for (int [] arrays: array) {
for (int num:arrays) {
if (num!=0)
number++;
}
}
int [][] arrayX=new int[number+1][3];
arrayX[0][0]=array.length;
arrayX[0][1]=array[0].length;
arrayX[0][2]=number;
int num=1;
for (int i = 0; i <array.length ; i++) {
for (int j = 0; j <array[i].length ; j++) {
if(array[i][j]!=0)
{
arrayX[num][0]=i;
arrayX[num][1]=j;
arrayX[num][2]=array[i][j];
num++;
}
}
}
return arrayX;
}
还原稀疏数组
public static int [][] arraysH(int[][] array)
{
int [][] arrayY=new int[array[0][0]][array[0][1]];
for (int i=1;i<=array[0][2];i++)
{
arrayY[array[i][0]][array[i][1]]=array[i][2];
}
return arrayY;
}
输出
public static void arrays(int[][] array)
{
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();
}
}