*/
#include <stdio.h> #define M 6 #define N 7 #define MaxSize 100 //矩阵中非零元素最多个数 typedef int ElemType; typedef struct { int r; //行号 int c; //列号 ElemType d; //元素值 } TupNode; //三元组定义 typedef struct { int rows; //行数 int cols; //列数 int nums; //非零元素个数 TupNode data[MaxSize]; } TSMatrix; //三元组顺序表定义 void CreatMat(TSMatrix &t,ElemType A[M][N]); //从一个二维稀疏矩阵创建其三元组表示 bool Value(TSMatrix &t,ElemType x,int i,int j); //三元组元素赋值 bool Assign(TSMatrix t,ElemType &x,int i,int j); //将指定位置的元素值赋给变量 void DispMat(TSMatrix t);//输出三元组 void TranTat(TSMatrix t,TSMatrix &tb);//矩阵转置 bool MatAdd(TSMatrix a,TSMatrix b,TSMatrix &c) { int i,j; ElemType va,vb,vc; if (a.rows!=b.rows || a.cols!=b.cols) return false; //行数或列数不等时不能进行相加运算 c.rows=a.rows; c.cols=a.cols; //c的行列数与a的相同 c.nums=0; for(i=0; i<M; i++) for(j=0; j<N; j++) { Assign(a,va,i,j); Assign(b,vb,i,j); vc=va+vb; if(vc) Value(c,vc,i,j); } return true; } int main() { TSMatrix ta,tb,tc; int A[M][N]= { {0,0,1,0,0,0,0}, {0,2,0,0,0,0,0}, {3,0,0,0,0,0,0}, {0,0,0,5,0,0,0}, {0,0,0,0,6,0,0}, {0,0,0,0,0,7,4} }; int B[M][N]= { {0,0,10,0,0,0,0}, {0,0,0,20,0,0,0}, {0,0,0,0,0,0,0}, {0,0,0,50,0,0,0}, {0,0,20,0,0,0,0}, {0,0,0,10,0,0,4} }; CreatMat(ta,A); CreatMat(tb,B); printf("A:\n"); DispMat(ta); printf("B:\n"); DispMat(tb); if(MatAdd(ta, tb, tc)) { printf("A+B:\n"); DispMat(tc); } else { printf("相加失败\n"); } return 0; }