稀疏矩阵的压缩存储
对于稀疏矩阵中的任意一个非零元素,出来存放非零元素的值外,还需要同时存储它所在的行,列的位置,反之,用一个三元组可以唯一确定一个非零元素。
稀疏矩阵的三元组表示的结点结构定义:
public class TripleNode {
public int row;
public int column;
public int value;
public TripleNode(int row, int column, int value) {
this.row = row;
this.column = column;
this.value = value;
}
public TripleNode(){
this(0,0,0);
}
}
三元组的顺序表类定义如下:
public class SparseMatix {
public TripleNode data[];
public int rows;
public int cols;
public int nums; // 非零元素个数
public SparseMatix(int maxSize){
data = new TripleNode[maxSize];
for(int i=0;i<data.length;i++){
data[i] = new TripleNode();
}
rows = 0;
cols = 0;
nums = 0;
}
// 打印表
public void prinMatrix(){
int i;
System.out.println("稀疏矩阵的三元组存储结构:");
System.out.println("行数:"+rows+" ,列数:"+cols+",非零元素个数:"+nums);
for(i= 0;i<nums;i++){
System.out.println(data[i].row+"\t"+data[i].column+"\t"+data[i].value);
}
}
// 初始化
public SparseMatix(int mat[][]){
int i,j,k=0,count = 0;
rows = mat.length; // 行数等于数组的长度
cols = mat[0].length; // 列数
for(i = 0; i<mat.length;i++){
for(j = 0;j<mat[i].length;j++){
if(mat[i][j]!=0){
count++;
}
}
}
nums = count;
data = new TripleNode[nums];
for(i= 0;i<mat.length;i++){
for(j = 0;j<mat[i].length;j++)
{
if(mat[i][j]!=0)
{
data[k] = new TripleNode(i,j,mat[i][j]);
k++;
}
}
}
}
// 转置
public SparseMatix transpose(){
SparseMatix tm = new SparseMatix(nums);
tm.cols = rows;
tm.rows = cols;
tm.nums = nums;
int q = 0;
for(int col = 0;col<cols;col++){
for(int p = 0;p<nums;p++){
if(data[p].column == col){
tm.data[q].row = data[p].column;
tm.data[q].column = data[p].row;
tm.data[q].value = data[p].value;
q++;
}
}
}
return tm;
}
public SparseMatix fasttanspose(){
SparseMatix tm = new SparseMatix(nums);
tm.cols = rows;
tm.rows = cols;
tm.nums = nums;
int i,j,k=0;
int [] num,cpot;
if(nums>0){
num = new int[cols];
cpot = new int[cols];
for(i = 0;i<cols;i++){
num[i] = 0;
}
for(i = 0;i<nums;i++)
{
j = data[i].column;
num[j]++;
}
cpot[0] = 0;
for(i = 1;i<cols;i++){
cpot[i] = cpot[i-1] + num[i-1];
}
for(i = 0;i<nums;i++){
j = data[i].column;
k = cpot[j];
tm.data[k].row = data[i].column;
tm.data[k].column = data[i].row;
tm.data[k].value = data[i].value;
cpot[j]++;
}
}
return tm;
}
}
公共类:
public class Example4_6 {
public static void main(String[] args){
int m[][]={
{0,0,8,0,0,0},{0,0,0,0,0,0},{5,0,0,0,16,0},{0,0,18,0,0,0},{0,0,0,9,0,0}
};
SparseMatix sm = new SparseMatix(m);
SparseMatix tm = sm.transpose();
sm.prinMatrix();
tm.prinMatrix();
}
}
最后的效果如图: