关注 “弋凡”(YiFan)微信公众号吧 记录简单笔记 做你的最爱
稀疏数组可以看作普通二维数组的压缩,这里的普通数组指无效数据远大于有效数据
稀疏数组分为3
列
行 列 值
r1 c1 v1
r2 c2 v2
... ... ...
普通二维数组 - 无效数据远远大于有效数据
0 0 0 0 0 0 0 0 0 0 0
0 1 0 0 0 0 0 0 0 0 0
0 0 2 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 0 0 0 0 0 0 0
0 0 0 0 0 0 0 0 0 0 0
稀疏数组
11 11 3
1 1 1
2 2 2
2 4 2
package com.yifan.nolinear;
import java.io.*;
/**
* @Author YIFan
* @Date 2020/6/7 17:49
* @Version 1.0
*/
// 稀疏数组
public class SparseArray {
public static void main(String[] args) throws IOException {
// 创建一个二维数组 11*11
// 0 表示没有数组 1 表示黑子 2 表示 白子
int[][] chessArry = new int[11][11];
chessArry[1][1] = 1;
chessArry[2][2] = 2;
chessArry[2][4] = 2;
// 输错原始数组
System.out.println("原始数组...");
for (int[] row : chessArry) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
int sum = 0;
//将二维数组转化为稀疏数组
//1,二维数组得到非零数据的个数
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArry[i][j] != 0 ){
sum++;
}
}
}
//2,创建对应的稀疏数组
int sparseArr[][] = new int[sum+1][3];
// 给稀疏数组赋值
// 行数
sparseArr[0][0] = 11;
// 列数
sparseArr[0][1] = 11;
// 有效数
sparseArr[0][2] = sum;
//3,遍历二维数组,将非0的值存到sparseArr中
//------> (稀疏数组格式) 行 列 值
int count = 0; // 用于记录第几个是非0数据
for (int i = 0; i < 11; i++) {
for (int j = 0; j < 11; j++) {
if(chessArry[i][j] != 0 ){
count++;
sparseArr[count][0] = i;
sparseArr[count][1] = j;
sparseArr[count][2] = chessArry[i][j];
}
}
}
//4,输出稀疏数组
System.out.println();
System.out.println("稀疏数组为....");
//写入到文件中
File file = new File("d:/a.data");
FileOutputStream in = new FileOutputStream(file);
for (int i = 0; i < sparseArr.length; i++) {
String str = sparseArr[i][0]+"-"+sparseArr[i][1]+"-"+sparseArr[i][2]+"\n";
in.write(str.getBytes());
System.out.printf("%d\t%d\t%d\t\n",sparseArr[i][0],sparseArr[i][1],sparseArr[i][2]);
}
System.out.println("写入文件成功...");
in.close();
//5,将稀疏数组还原成原始的二维数组
/*
* 1,先读取稀疏数组的第一行,根据第一行数据,创建原始的二维数组
* 2,在读取稀疏数组的后几行数据,并赋值给二维数组
* */
// int[][] chessArr2 = new int[sparseArr[0][0]][sparseArr[0][1]];
// 从文件中读取
int[][] chessArr2 = null;
BufferedReader reader = null;
System.out.println("以行为单位读取文件内容,一次读一整行:");
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
System.out.println("line " + line + ": " + tempString);
String[] split = tempString.split("-");
int row = Integer.parseInt(split[0]);
int col = Integer.parseInt(split[1]);
if(line==1){
chessArr2 = new int[row][col];
}else {
chessArr2[row][col] = Integer.parseInt(split[2]);
}
line++;
}
reader.close();
// 用稀疏数组进行还原
// for (int i = 1; i < sparseArr.length; i++) {
// int row = sparseArr[i][0];
// int col = sparseArr[i][1];
// chessArr2[row][col] = sparseArr[i][2];
// }
System.out.println("新的二维数组...");
for (int[] row : chessArr2) {
for (int data : row) {
System.out.printf("%d\t", data);
}
System.out.println();
}
}
}