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 2 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 2
package com.wang.array;
public class Demo09 {
public static void main(String[] args) {
int[][] a = new int[11][11];
a[1][2]=1;
a[2][3]=2;
for (int[] ints : a) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();//输出原始数组
}
int sum=0; //提取有效值数量
for (int i = 0; i < 11; i++) {
for (int i1 = 0; i1 < 11; i1++) {
if(a[i][i1]!=0){
sum++;
}
}
}
System.out.println("有效值数量:"+sum); //提取有效值数量
////////创建一个稀疏数组
int[][] b = new int[sum+1][3];
b[0][0]=11; //确定表头
b[0][1]=11;
b[0][2]=sum;
//遍历二维数组,将非零值存放稀疏数组中
int count = 0;
for (int i = 0; i < a.length; i++) {
for (int k = 0; k < a[i].length; k++) {
if(a[i][k]!=0){
count++;
b[count][0]=i;
b[count][1]=k;
b[count][2]=a[i][k];
}
}
}
//输出稀疏数组
for (int[] ints : b) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
///////////////////还原稀疏数组
int[][] c =new int[b[0][0]][b[0][1]]; //定义数组行列数
for (int i = 1; i < b.length; i++) {
c[b[i][0]][b[i][1]] = b[i][2];
}
//打印
for (int[] ints : c) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
}
}
标签:11,26,int,稀疏,System,++,数组,out
From: https://www.cnblogs.com/PedroPascal/p/17098320.html