稀疏矩阵

Posted FZZ98

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了稀疏矩阵相关的知识,希望对你有一定的参考价值。

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

以上是关于稀疏矩阵的主要内容,如果未能解决你的问题,请参考以下文章

稀疏矩阵的运算

如何写成高性能的代码:巧用稀疏矩阵节省内存占用

如何写成高性能的代码:巧用稀疏矩阵节省内存占用

Python 稀疏矩阵访问元素

小代码 单链表之反转 然后交错重连+稀疏矩阵

优化 Scipy 稀疏矩阵