将数组导入java待完善
package datastructure;
import java.io.*;
public class SpareArray {
public static void main(String[] args) throws IOException {
// 创建原始的数组
int chessArr1[][] = new int[11][11];
chessArr1[1][2] = 1;
chessArr1[2][4] = 2;
chessArr1[4][5] = 2;
// 输出原始的数组
System.out.println("原始的二维数组:");
for(int [] row:chessArr1){
for (int data : row){
// 格式化输出printf
System.out.printf("%d\t",data);
}
System.out.println();
}
// 将二维数组转化为稀疏数组
int sum = 0;
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if(chessArr1[i][j] != 0)
sum++;
}
}
// 创建对应的稀疏数组
int[][] sparseArr = new int[sum + 1][3];
sparseArr[0][0] = chessArr1.length;
sparseArr[0][1] = chessArr1[0].length;
sparseArr[0][2] = sum;
// 遍历数组,将非0值存放到sparseArr中
int count = 0;//记录第几个非0的数据
for (int i = 0; i < chessArr1.length; i++) {
for (int j = 0; j < chessArr1[0].length; j++) {
if(chessArr1[i][j] != 0){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArr1[i][j];
}
}
}
// 将稀疏数组写入到文件
File file = new File("E:\\map.txt");
FileWriter out = new FileWriter(file);
System.out.println("稀疏数组如下:");
for (int i = 0; i < sparseArr.length; i++) {
System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
out.write(sparseArr[i][0] + "\t" + sparseArr[i][1] + "\t" + sparseArr[i][2] + "\n");
}
out.close();
FileReader fileReader = new FileReader("E:\\map.txt");
BufferedReader bufferedReader = new BufferedReader(fileReader);
String s = null;
while ((s = bufferedReader.readLine()) != null){
System.out.println(s);
}
// 将spareArr 转化为原始的二维数组
int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
for (int i = 1; i < sparseArr.length; i++) {
chessArr2[sparseArr[i][0]][sparseArr[i][1]] = sparseArr[i][2];
}
System.out.println("恢复后的二维数组");
for (int[] row : chessArr2){
for (int data : row){
System.out.printf("%d\t",data);
}
System.out.println();
}
}
}

京公网安备 11010502036488号