版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_30648823/article/details/79764665
// 数组_稀疏矩阵.cpp: 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdio.h"
#include "malloc.h"
#define MAXSIZE 400
//定义三元表
typedef struct sanyuanbiao {
struct sanyuanbiao *next;
int i, j, v;
}SanYuanBiao;
//定义数组
typedef struct arrs {
int data[MAXSIZE + 1];
int x,y;
}Arrs;
//初始化三元表
SanYuanBiao *Init() {
SanYuanBiao *B;
B = (SanYuanBiao *)malloc(sizeof(sanyuanbiao));
B->next = NULL;
return B;
}
//初始化数组
Arrs *InitA() {
Arrs *A;
A = (Arrs *)malloc(sizeof(arrs));
A->data[1] = 0;
A->x = 0;
A->y = 0;
return A;
}
//数组归零
void GuiLing(Arrs *A) {
int i = MAXSIZE;
while (i) {
A->data[i] = 0;
i--;
}
}
//打印数组
void PrintA(Arrs *A) {
for (int i = 1; i <= A->y; i++) {
for (int j = 1; j <= A->x; j++) {
printf("%5d", A->data[(i - 1)*A->x + j]);
}
printf("\n");
}
}
//将二维数组转换为三元表
void ZhuanHuan(Arrs *A,SanYuanBiao *B) {
SanYuanBiao *p;
SanYuanBiao *wei;
for (int t = 1; t <= A->x*A->y; t++) {
wei = B;
if (A->data[t] != 0) {
p = (SanYuanBiao*)malloc(sizeof(sanyuanbiao));
p->i = t / A->x + 1;
p->j = t%A->x;
p->v = A->data[t];
for (; wei->next != NULL;) {
wei = wei->next;
}
p->next = wei->next;
wei->next = p;
}
}
}
//打印三元表
void PrintS(SanYuanBiao *B) {
SanYuanBiao *p;
p = B->next;
for (int i = 0;p!=NULL; i++) {
printf("第%d个 %5d %5d %5d\n", i + 1, p->i, p->j, p->v);
p = p->next;
}
}
//数组换方向
void HuanFangXiang(Arrs *A,Arrs *A1 ) {
A1->x = A->y;
A1->y = A->x;
for (int i = 1; i <= A->x; i++) {
for (int j = 1; j <= A->y; j++) {
A1->data[(i - 1)*A1->x + j] = A->data[(j - 1)*A->x + i];
}
}
}
int main()
{
//初始化三元表
SanYuanBiao *B;
B = Init();
//弄一个稀疏矩阵
//初始化数组
Arrs *A;
A = InitA();
//归零
GuiLing(A);
//写入数组的大小以及数据
A->x = 6;
A->y = 6;
A->data[(1 - 1) * A->x + 3] = 16;
A->data[(2 - 1) * A->x + 2] = 18;
A->data[(3 - 1) * A->x + 4] = 6;
A->data[(3 - 1) * A->x + 6] = -15;
A->data[(4 - 1) * A->x + 5] = 12;
A->data[(5 - 1) * A->x + 1] = 97;
printf("打印出稀疏矩阵\n");
PrintA(A);
//转换为三元
ZhuanHuan(A, B);
printf("打印出来的三元表\n");
PrintS(B);
//换方向
//初始化一个数组
Arrs *A1;
A1 = InitA();
//换
HuanFangXiang(A, A1);
printf("换完方向后的数组为:\n");
PrintA(A1);
//转换换方向后的三元表
//初始化一个
SanYuanBiao *B1;
B1 = Init();
ZhuanHuan(A1, B1);
printf("打印出来的三元表\n");
PrintS(B1);
return 0;
}