对于稀疏矩阵,为了不浪费空间,我们可以用一个三元组来记录下它的位置与权值;
转置:将<i,j>元素与<j,i>元素互换;
结构体:根据矩阵里非0元素动态分配n个三元组空间;
typedef struct {
int i;
int j;
int e;
}Triple,*TriplePtr;
typedef struct {
int num;
TriplePtr element;
}CompressMatrix,*CompressMatrixPtr;
矩阵的读取与转置:
1.确定非0元素count个
2.转置
CompressMatrixPtr Read_PressMatrix(matrixPtr Matrix) {
//read matrix
int cnt = 0;
for (int i = 0; i < Matrix->row; i++) {
for (int j = 0; j < Matrix->col; j++) {
if (Matrix->M[i][j] != 0) cnt++;
}
}
//Press
CompressMatrixPtr ResultTriple = (CompressMatrixPtr)malloc(sizeof(CompressMatrix));
ResultTriple->element = (TriplePtr)malloc(sizeof(Triple) * cnt);
int count = 0;
for (int j = 0; j < Matrix->col; j++) {
for (int i = 0; i < Matrix->row; i++) {
if (Matrix->M[i][j] != 0) {
ResultTriple->element[count].i = j;
ResultTriple->element[count].j = i;
ResultTriple->element[count].e = Matrix->M[i][j];
count++;
}
}
}
ResultTriple->num = count;
return ResultTriple;
}
输出压缩矩阵:pass
void output_triple(CompressMatrixPtr T) {
for (int i = 0; i < T->num; i++) {
printf("(%d,%d) : %d \n", T->element[i].i, T->element[i].j, T->element[i].e);
}
}
效果截图: