数据结构--稀疏数组

admin2024-04-03  0

package com.dhu.sparsearray;

public class SparseArrsy {
    public static void main(String[] args) {
        int chessArr1[][] = new int[11][11];
        chessArr1[1][2] = 1;
        chessArr1[2][3] = 2;
        chessArr1[3][4] = 11;
        System.out.printf("原始二维数组");
        for (int[] row : chessArr1){
            for (int data : row){
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }
        //1. 遍历二维数组,找到非零个数
        int sum = 0;
        for (int i = 0; i < chessArr1.length; i++){
            for (int j = 0; j < chessArr1.length; j++){
                if(chessArr1[i][j] != 0){
                    sum++;
                }
            }
        }
        //System.out.println(sum);

        //2.创建对应稀疏数组
        int sparseArr[][] = new  int[sum + 1][3];
        sparseArr[0][0] = 11;
        sparseArr[0][1] = 11;
        sparseArr[0][2] = sum;

        //遍历二维数组,将非0值存放到sparseArr
        int count = 0;//用于记录第几个非零值
        for (int i = 0; i < chessArr1.length; i++){
            for (int j = 0; j < chessArr1.length; j++){
                if(chessArr1[i][j] != 0){
                    count++;
                    sparseArr[count][0] = i;
                    sparseArr[count][1] = j;
                    sparseArr[count][2] = chessArr1[i][j];
                }
            }
        }

        // 输出稀疏数组
        System.out.println();
        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]);
        }
        System.out.println();

        //稀疏数组--》二维数组
        //先读取稀疏数组的行列,创建二维数组,

        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();
        System.out.println("恢复后的二维数组");
        for (int[] row : chessArr2){
            for (int data : row){
                System.out.printf("%d\t", data);
            }
            System.out.println();
        }

    }
}
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明原文出处。如若内容造成侵权/违法违规/事实不符,请联系SD编程学习网:675289112@qq.com进行投诉反馈,一经查实,立即删除!