稀疏矩阵中的非零元素个数较少,因为为了节省存储空间,采用三元组来保存这些为数不多的非零元素.
表示一个系数矩阵的思路:先以三元组的形式将稀疏矩阵进行构建, 再对整个稀疏矩阵中的节点属性进行表示
对非零元素进行表示的三元组用结构体来进行实现:
typedef struct{
int i,j;//非零元素的行下标和列下标
int data;//非零元素的数值
}triple;
对稀疏矩阵同样用结构体来进行表示
#define number 20
typedef struct{
int m,n,num;
triple data[number];//通过数组将非零元素的位置和数值信息进行汇总记录
}
对以三元组表示的稀疏矩阵进行转置思路:
-
首先要初始化一个以三元组形式表示的矩阵,存储原矩阵的转置矩阵,即创建了一个结构体变量要为该结构体变量开辟空间
如果没有该步骤,将出现
段错误
,即非法的内存訪问
,因为在将原矩阵的元素放入转置矩阵的同时却没有为转置矩阵开辟空间,无法存储该变量 -
通过矩阵的列序进行索引,在每一列中都对三元表中的元素进行检索,检索到就进行行列下标的互换并赋原值
在该步骤中要注意两个结构体变量之间的引用关系,首先从
三元组表示的矩阵结构体
中寻找元素,然后在节点信息结构体
中对应该元素的具体下标和值属性两个矩阵要同时分别进行三元组中元素的检索和赋值,所以定义两个变量来分别表示两个三元组中元素的位置,并且最后要进行变量的更新
完整程序(参照PTA题目要求以及主测试程序):
#include <stdio.h>
#include <stdlib.h>
#define M 100
struct tripletable *trans(struct tripletable *t1);
// describe the node attributes of the original matrix and transpose matrix
struct node
{
int i, j, v;
};
// the tripletable to store the non-zero elements
struct tripletable
{
struct node S[M];
int m, n, t; // m,n is the row,column of the matrix, t is the number of non-zero element
};
/*
craete a new matrix represented by tripletable
*/
struct tripletable *create()
{
int i;
// need to open up space tp create a struct variable
struct tripletable *head = (struct tripletable *)malloc(sizeof(struct tripletable));
scanf("%d%d%d", &(head->m), &(head->n), &(head->t));
for (i = 0; i < head->t; i++)
scanf("%d%d%d", &(head->S[i].i), &(head->S[i].j), &(head->S[i].v));
return head;
}
void print(struct tripletable *head)
{
int i;
for (i = 0; i < head->t; i++)
printf("%d %d %d\n", (head->S[i].i), (head->S[i].j), (head->S[i].v));
system("pasue");
}
int main()
{
struct tripletable *head, *t2; // variable:head is the name of the original matrix represented by tripletable
head = create();
t2 = trans(head);
print(t2);
system("pasue");
return 0;
}
/*
matrix transpose
the first thing is initial the transpose matrix, open up space for it
the second thing is to fill in the elements
*/
struct tripletable *trans(struct tripletable *t1) // t1 is original matrix
{
struct tripletable *t2 = (struct tripletable *)malloc(sizeof(struct tripletable)); // define t2 is tanspose matrix for t1
// initial the tranpose matrix
t2->m = t1->n;
t2->n = t1->m;
t2->t = t1->t;
int c = 0; // the row number of the tranpose matrix
int p = 0; // the element count of the triple for original matrix
int q = 0; // the element count of the triple for tranpose matrix
for (c = 0; c < t1->n; c++)
{ // traverse the column
for (p = 0; p < t1->t; p++)
{ // traverse the triple
if (t1->S[p].j == c)
{
t2->S[q].i = t1->S[p].j;
t2->S[q].j = t1->S[p].i;
t2->S[q].v = t1->S[p].v;
q++;
}
}
}
return t2;
}