数据结构---二维数组与稀疏数组的转化(demo,能保存值硬盘)

package com.xwtec.sparsearray;

import java.io.*;

/**
 * 二维数组和稀疏数组的相互转换
 * @Author: zt
 * @Date: 2021/5/19 21:36
 */
public class SparseArray {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        //定义一个11*11的二维数组
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][7] = 8;
        //遍历二维数组
        for (int[] row:chessArr1) {
            for(int i: row){
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }
        //二维数组转换成稀疏数组
        //1、获取二维数组中所有非0的个数;
        int sum = 0;
        for (int[] row:chessArr1) {
            for (int i:row) {
                if(i !=0){
                    sum++;
                }
            }
        }
        //2.创建一个稀疏数组
        int sparseArr[][] = new int[sum + 1][3];
        sparseArr[0][0]=11;
        sparseArr[0][1]=11;
        sparseArr[0][2]=sum;
        //3.稀疏数组赋值
        int count=0;
        for (int i = 0; i < 11 ; i++) {
            for (int j = 0; j <11 ; j++) {
                if (chessArr1[i][j] != 0){
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }
        //4.遍历稀疏数组
        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]);
        }

        //输出流,将棋盘数据保存下来
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("C:/Users/Theo_zhu/Desktop/map.data")));
        objectOutputStream.writeObject(sparseArr);
        objectOutputStream.close();

        //输入流:读取存档文件
        ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream(new File("C:/Users/Theo_zhu/Desktop/map.data")));
        Object o = inputStream.readObject();
        inputStream.close();
        int sparseArr1[][] = (int[][])o;

        //将稀疏数组恢复成二维数组
        int chessArr2[][] = new int[sparseArr1[0][0]][sparseArr1[0][1]];
        for (int i = 1; i <sparseArr.length ; i++) {
            chessArr2[sparseArr1[i][0]][sparseArr1[i][1]] = sparseArr1[i][2];
        }

        for (int[] row:chessArr2) {
            for(int i: row){
                System.out.printf("%d\t",i);
            }
            System.out.println();
        }


    }
}

 

posted @ 2021-05-19 23:16  J.....ava  阅读(51)  评论(0)    收藏  举报