稀疏矩阵的压缩与还原——基于java

稀疏矩阵的压缩与还原

在main函数的内部进行了简单的测试。

/**
 * 实现将数组转换为稀疏数组保存和将稀疏数组还原为实际数组
 */
public class Demo03 {
    public static void main(String[] args) {
        int[][] array = new int[10][10];

        //只有以下四个位置不为0
        array[2][3] = 1;
        array[3][5] = 2;
        array[1][7] = 1;
        array[2][8] = 2;

        //数组原貌
        System.out.println("二维数组原貌:");
        printArray(array);

        //进行稀疏矩阵转换
        int[][] result = sparseChange(array);
        System.out.println("对应的稀疏矩阵:");
        printArray(result);

        //将稀疏矩阵进行还原
        int[][] result2 = changeFromSparse(result);
        System.out.println("还原后的数组:");
        printArray(result2);

    }

    //将数组转换为稀疏数组
    public static int[][] sparseChange(int[][] a){
        int sum = 0;   //记录数组中元素不为0的个数
        for (int[] ints : a) {
            for (int anInt : ints) {
                if(anInt != 0){
                    sum++;
                }
            }
        }

        int[][] result = new int[sum + 1][3];  //存储方式一定为3列 sum+1行,第一行存储原数组大小和不为0的元素个数

        result[0][0] = a.length;
        result[0][1] = a[0].length;
        result[0][2] = sum;

        int count = 0;   //计数器

        for(int i = 0; i < a.length; i++){
            for(int j = 0; j < a[i].length; j++){
                if(a[i][j] != 0){
                    count++;
                    result[count][0] = i;
                    result[count][1] = j;
                    result[count][2] = a[i][j];
                }
            }
        }
        return result;
    }

    //将稀疏矩阵还原为实际矩阵
    public static int[][] changeFromSparse(int[][] a){
        int[][] result = new int[a[0][0]][a[0][1]];
        for (int i = 1; i < a.length; i++){
            result[a[i][0]][a[i][1]] = a[i][2];
        }
        return result;
    }

    //打印输出二维数组。因为要多次打印,所以封装一个函数
    public static void printArray(int[][] a){
        for (int[] ints : a) {
            for (int anInt : ints) {
                System.out.print(anInt + "\t");
            }
            System.out.println();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值