package DataStructures;
public class XishuArray {
public static void main(String[] args) {
int chess[][] = new int[11][11];
chess[1][2] = 1;
chess[2][3] = 2;
//其实就是有两个有用的值
for (int[] arr : chess) {
for (int e : arr) {
System.out.printf("%d\t",e);//重点
}
System.out.println();
}
int count =0;
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess.length; j++) {
if (chess[i][j]!=0) {
count++;
}
}
}
System.out.println("count = " + count);//找到有效数值的个数。
int xishu[][] = new int[count+1][3];//有效值,加总数,横坐标,纵坐标,保存为值,以及真正的值
xishu[0][0] = 11;
xishu[0][1] = 11;
xishu[0][2] = count;
int index = 1; //其实列的值可以写死了。就是行的值变化。
for (int i = 0; i < chess.length; i++) {
for (int j = 0; j < chess.length; j++) {
if (chess[i][j]!=0) {
xishu[index][0]=i;
xishu[index][1]=j;
xishu[index][2]=chess[i][j];
index++;
}
}
}
//打印我们的稀疏数组
for (int[] arr : xishu) {
for (int e : arr) {
System.out.printf("%d\t",e);
}
System.out.println();
}
int [] [] odlarr = new int [xishu[0][0]][xishu[0][1]];
for (int i = 1; i < xishu.length; i++) {
odlarr[xishu[i][0]][xishu[i][1]]=xishu[i][2];
}
for (int[] arr : odlarr) {
for (int e : arr) {
System.out.printf("%d\t",e);//重点
}
System.out.println();
}
}
}
稀疏数组的实现和恢复
最新推荐文章于 2022-04-25 16:03:00 发布