首页 > 其他 > 详细

稀疏矩阵

时间:2021-05-14 09:51:25      阅读:17      评论:0      收藏:0      [点我收藏+]
public class ArraysDemo {

    public static void main(String[] args) {
        // 初始化矩阵
        int [][] a1 = new int[11][11];
        a1[2][1]=1;
        a1[6][6]=2;
        a1[10][10]=3;
        System.out.println("original matrix:");
        printArray(a1);

        // 统计稀疏矩阵大小
        int num = 0;
        for (int i = 0; i < a1.length; i++) {
            for (int j = 0; j < a1[i].length; j++) {
                if (a1[i][j]!=0) num++;
            }
        }

        // 压缩
        int[][] a2 = compressArray(a1, num);
        System.out.println("compress matrix:");
        printArray(a2);

        // 还原
        int[][] a3 = recoveryArray(a2);
        System.out.println("recovery matrix:");
        printArray(a3);

    }

    /**
     * recoveryArray
     * @param ints
     * @return
     */
    private static int[][] recoveryArray(int[][] ints) {
        int[][] a3 = new int[11][11];
        for (int i = 1; i < ints.length; i++) {
            for (int j = 0; j < ints[i].length; j++) {
                a3[ints[i][0]][ints[i][1]]=ints[i][2];
            }
        }
        return a3;
    }

    /**
     * compressArray
     * @param a1
     * @param num
     * @return
     */
    private static int[][] compressArray(int[][] a1,int num) {
        // 创建一个稀疏矩阵
        int[][] a2 = new int[num+1][3];
        a2[0][0] = 11;
        a2[0][1] = 11;
        a2[0][2] = num;
        // 计数
        int count = 0;
        for (int i = 0; i < a1.length; i++) {
            for (int j = 0; j < a1[i].length; j++) {
                if (a1[i][j]!=0){
                    count++;
                    a2[count][0]=i;
                    a2[count][1]=j;
                    a2[count][2]=a1[i][j];
                }
            }
        }
        return a2;
    }

    /**
     * printArray
     * @param a1
     */
    public static void printArray(int[][] a1){
        for (int[] ints : a1) {
            for (int anInt : ints) {
                System.out.print(anInt+"\t");
            }
            System.out.println();
        }
    }
}

运行效果

original matrix:
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	1	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	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	3	
compress matrix:
11	11	3	
2	1	1	
6	6	2	
10	10	3	
recovery matrix:
0	0	0	0	0	0	0	0	0	0	0	
0	0	0	0	0	0	0	0	0	0	0	
0	1	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	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	3

稀疏矩阵

原文:https://www.cnblogs.com/pipacam/p/14767010.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!