测试:转化 10*10 的稀疏数组
转化稀疏数组
private static int[][] compressArray(int[][] resource) {
int count = 0;
for (int[] data : resource) {
for (int d : data) {
if (d != 0) count++;
}
}
int[][] res = new int[count + 1][3];
res[0][0] = 10;
res[0][1] = 10;
res[0][2] = count;
count = 1;
for (int i = 0; i < resource.length; i++) {
for (int j = 0; j < resource[i].length; j++) {
if (resource[i][j] != 0) {
res[count][0] = i;
res[count][1] = j;
res[count][2] = resource[i][j];
count++;
}
}
}
return res;
}
恢复二维数组
private static int[][] reductionArray(int[][] resource) {
int[][] target = new int[resource[0][0]][resource[0][1]];
for (int item = 1; item < resource.length; item++) {
for (int it = 1; it < resource[item].length; it++) {
target[resource[item][0]][resource[item][1]] = resource[item][2];
}
}
return target;
}
自定义输出语句
private static void myOut(int[][] resource) {
for (int[] data : resource) {
for (int item : data) {
System.out.printf("%d\t", item);
}
System.out.println();
}
}
测试:
public static void main(String[] args) {
int[][] dates = new int[10][10];
int[][] res;
dates[1][2] = 1;
dates[2][3] = 2;
System.out.println("原始数据");
myOut(dates);
System.out.println("转换稀疏数组");
res = compressArray(dates);
myOut(res);
System.out.println("还原稀疏数组");
myOut(reductionArray(res));
}
控制台结果
原始数据
0 0 0 0 0 0 0 0 0 0
0 0 1 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
转换稀疏数组
10 10 2
1 2 1
2 3 2
将稀疏数组还原
0 0 0 0 0 0 0 0 0 0
0 0 1 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
Process finished with exit code 0