二维数组转稀疏数组的思路:
- 遍历原始的二维数组,得到有效数据的个数 sum;
- 根据sum就可以创建系数数组sparseArray int[sum+1][3];
- 将二维数组的有效数据存入稀疏数组。
稀疏数组转原始的二维数组的思路:
- 先读取稀疏数组的第一行,根据第一行的数据,创建原始的二维数组;
- 再读取稀疏数组的后几行数据,并赋给原始二维数组的对应位置。
代码实现
package com.atguiqu.sparsearray;
/**
* @Description
* @author Wdragon
* @version
* @date 2021年9月1日下午7:00:18
*
*/
public class SparseArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
//创建一个原始的二维数组 11*11
//0:表示无棋子;1:表示黑子;2:表示蓝色棋子
int chessArray[][] = new int[11][11];
chessArray[1][2] = 1;
chessArray[2][3] = 2;
//输出原始的二维数组
System.out.println("输出原始二维数组:");
for(int[] row : chessArray){
for(int data : row){
System.out.printf("%d\t",data);
}
System.out.println();
}
//将二维数组转为稀疏数组的思路
//遍历二维数组,得到非零数据的个数
int sum = 0;
for(int i = 0; i < chessArray.length; i++){
//System.out.println(i);
for(int j = 0; j < chessArray[0].length; j++){
if(chessArray[i][j] != 0){
sum++;
}
}
}
System.out.println();
System.out.println("sum=" + sum);
//创建对应的稀疏数组
int sparseArray[][] = new int[sum + 1][3];
//给稀疏数组赋值
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
//二维数组的非零值存放进稀疏数组
int count = 0;
for(int i = 0; i < chessArray.length; i++){
//System.out.println(i);
for(int j = 0; j < chessArray[0].length; j++){
if(chessArray[i][j] != 0){
sparseArray[count + 1][0] = i;
sparseArray[count + 1][1] = j;
sparseArray[count + 1][2] = chessArray[i][j];
count++;
}
}
}
// 输出稀疏数组
System.out.println();
System.out.println("得到的稀疏数组为:");
for(int i = 0; i < sparseArray.length; i++){
System.out.printf("%d\t%d\t%d\t\n", sparseArray[i][0], sparseArray[i][1], sparseArray[i][2]);
}
//将稀疏数组转为二维数组
//先读取稀疏数组的第一行确定二维数组的大小
int chessArray2[][] = new int[sparseArray[0][1]][sparseArray[0][1]];
for(int i = 1; i < sparseArray.length; i++){
chessArray2[sparseArray[i][0]][sparseArray[i][1]] = sparseArray[i][2];
}
//输出恢复之后的二维数组(初始化的)
System.out.println("\n恢复后的二维数组:");
for(int row[] : chessArray2){
for(int data : row){
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}
测试结果
