三角矩阵压缩

三角矩阵压缩

关于三角矩阵的描述是,其非0元素呈三角状排列,三角矩阵又分上三角矩阵和下三角矩阵,如果我们用二维数组来储存三角矩阵的话,0元素会浪费很多的空间,因此我们可以用一维数组把矩阵进行压缩,下面给出一个java压缩下三角矩阵的例子:

package com.bikeqx.main;

public class Main {
    public static void main(String[] args) {
        Matrix matrix = new Matrix();
        matrix.compressMatrix();
        matrix.traverseCompressMatrix();
    }
}

class Matrix{
    //初始下三角矩阵 5阶矩阵
    int[][] triangularMatrix = {
            {1,0,0,0,0},
            {4,7,0,0,0},
            {6,9,5,0,0},
            {1,8,4,1,0},
            {2,3,0,9,6}
    };

    //压缩后的一维数组
    int[] matrix = new int[16];

    //遍历矩阵
    void traverse(){
        for(int row = 0;row < this.triangularMatrix.length;row++) {
            for(int column = 0;column < this.triangularMatrix[row].length;column++) {
                System.out.print(this.triangularMatrix[row][column] + " ");
            }
            System.out.println();
        }
    }

    //遍历压缩后的矩阵
    void traverseCompressMatrix() {
        for(int item : this.matrix) {
            System.out.println(item + " ");
        }
    }

    //压缩的矩阵
    void compressMatrix() {
        //一维数组的下标
        int index;
        for(int row = 0;row < this.triangularMatrix.length;row++) {
            for(int column = 0;column < this.triangularMatrix[row].length;column++) {
                //行号>列号
                if(row >= column) {
                    index = row * (row + 1)/2 + column;
                    this.matrix[index] = this.triangularMatrix[row][column];
                }
                else {
                    matrix[this.triangularMatrix.length - 1] = 0;
                }
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值