1、需求场景
- 当二维数组的大部分值是默认值0的时候,可以考虑使用稀疏数组,譬如:
![](https://img2020.cnblogs.com/blog/2031463/202012/2031463-20201221201631808-1060460070.png)
2、二维数组转换为稀疏数组
思路分析
- 记录数组有m行n列,有p个非零值--->对应到稀疏数组的第0行(遍历原始数组)
- 在稀疏数组中,记录原数组的非零值的行列坐标(x, y)和数值v---> 从第一行分别往下列出
![](https://img2020.cnblogs.com/blog/2031463/202012/2031463-20201221201644773-513998776.png)
3、稀疏数组还原为二维数组
- 由稀疏数组的第一行----->得到原始数组的行列数,就可以确定数组的大小
- 读取剩余的行,就可以填充原始数组。
4、例题实现
- 将二维数组转换为稀疏数组,然后存储到磁盘,实现棋盘的保存功能;
- 读取磁盘文件,恢复成为原来的棋盘,实现续上盘的功能;
![](https://img2020.cnblogs.com/blog/2031463/202012/2031463-20201221201702991-1459674607.png)
public class ExerciseArr {
public static void main(String[] args) {
int[][] chessArray = initArray();
int[][] sparseArray = ArrayToSparseArray(chessArray);
storeToDisk(sparseArray);
int[][] readFromDisk = readFromDisk();
for (int[] row : readFromDisk) {
for (int i : row) {
System.out.print(i + " ");
}
System.out.println();
}
}
public static int[][] initArray(){
int[][] chessArr = new int[11][11];
chessArr[1][2] = 1;
chessArr[2][3] = 2;
return chessArr;
}
public static int[][] ArrayToSparseArray(int[][] chessArray){
int sum = 0;
for (int[] row : chessArray) {
for (int data : row) {
if (data != 0)
sum++;
}
}
int[][] sparseArray = new int[sum+1][3];
sparseArray[0][0] = 11;
sparseArray[0][1] = 11;
sparseArray[0][2] = sum;
int sparseRow = 1;
for (int i = 0; i < chessArray.length; i++) {
for (int j = 0; j < 11; j++) {
if (chessArray[i][j] != 0){
sparseArray[sparseRow][0] = i;
sparseArray[sparseRow][1] = j;
sparseArray[sparseRow++][2] = chessArray[i][j];
}
}
}
return sparseArray;
}
public static int[][] sparseArrayToArray(int[][] sparseArray){
int[][] array = new int[sparseArray[0][0]][sparseArray[0][1]];
for (int i = 1; i <sparseArray.length; i++) {
array[sparseArray[i][0]][sparseArray[i][1]]=sparseArray[i][2];
}
return array;
}
public static void storeToDisk(int[][] sparseArray) {
DataOutputStream dos = null;
try {
dos = new DataOutputStream(new FileOutputStream(new File("storeArray.txt")));
for (int[] row : sparseArray) {
for (int data : row) {
dos.writeInt(data);
}
}
dos.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dos != null) {
dos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static int[][] readFromDisk() {
DataInputStream dis = null;
int[][] sparseArray = new int[0][];
try {
dis = new DataInputStream(new FileInputStream("storeArray.txt"));
sparseArray = new int[3][3];
for (int i = 0; i < sparseArray.length; i++) {
for (int j = 0; j < sparseArray[0].length; j++) {
sparseArray[i][j] = dis.readInt();
}
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (dis != null) {
dis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return sparseArray;
}
}
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步