三角矩阵压缩
关于三角矩阵的描述是,其非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;
}
}
}
}
}