稀疏数组:是一个多行三列的数组,第一行存的是原始数组的行,列,有效值数量;主要是压缩存储空间,例如五子棋完成存盘和续上盘的功能
转成稀疏数组存储就是:
11 11 2
1 2 1
2 3 2
代码实现:
/**
* @Description 稀疏数组
* @Author
* @Date
**/
public class SparseTest{
public static void main(String[] args) {
//初始化原始二维数组
int[][] num = new int[11][11];
num[1][2] = 1;
num[2][3] = 2;
//将二维数组转成稀疏数组
//1.计算总共有多少个有效值
int count = 0;
for (int[] ints : num) {
for (int anInt : ints) {
if(anInt!=0){
count++;
}
}
}
//2.初始化稀疏数组,数组行数=count+1
int[][] parse = new int[count+1][3];
//3.给稀疏数组赋值
parse[0][0] = num.length;
parse[0][1] = num[0].length;
parse[0][2] = count;
int index = 0;
for(int i=0;i<num.length;i++){
for(int j=0;j<num[i].length;j++){
if(num[i][j]!=0){
index++;
parse[index][0] = i;
parse[index][1] = j;
parse[index][2] = num[i][j];
}
}
}
//将稀疏数组存到文件中
BufferedWriter out;
{
try {
out = new BufferedWriter(new FileWriter("E:\\Java\\test\\map.data"));
for (int[] ints : parse) {
for (int anInt : ints) {
out.write(anInt+" ");
}
out.newLine();
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
BufferedReader in;
try {
in = new BufferedReader(new FileReader("E:\\Java\\test\\map.data"));
String line = "";
int rows = 0;
int cols = 0;
int sum = 0;
//读取第一行的值,获得原始数组几行几列,几个有效值
line = in.readLine();
String[] strings = line.split(" ");
rows = Integer.parseInt(strings[0]);
cols = Integer.parseInt(strings[1]);
sum = Integer.parseInt(strings[2]);
//初始化原始数组
int[][] ori = new int[rows][cols];
int start = 0;
while ((line = in.readLine())!=null){
start++;
if(start<=sum){
String[] split = line.split(" ");
ori[Integer.parseInt(split[0])][Integer.parseInt(split[1])] = Integer.parseInt(split[2]);
}
}
for (int[] ints : ori) {
for (int anInt : ints) {
System.out.print(anInt+"\t");
}
System.out.println();
}
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}