#include<stdio.h>
#include <stdlib.h>
#define MAXSIZE 100
#define ElementType int
//扫描数组将非零元素存在三元组里面
typedef struct
{
int row, col;//非零元素的下标
ElementType e;//非零元素
}Triple;
typedef struct
{
Triple data[MAXSIZE];
int len;//非0元素的个数
}TSMatrix;
void FastTranse(TSMatrix *A, TSMatrix *B)//方形矩阵的转置
{
//上述A的三元表已经写出,从三元表里面重新排序
int position[MAXSIZE] = {0};
B->len = A->len;//将从A中获得的长度给B
for (int t = 0; t < A->len; t++)
{
position[A->data[t].col]++;
}
position[0] = 1;
for (int i = 1; i < 4; i++)
{
position[i] = position[i - 1] + position[i];//将第1列中获取的个数传给第0列以此类推
}
for (int p = 0; p < A->len; p++)
{
int col = A->data[p].col-1;//因为你传递了位置 再加之右值获得的是整数>=1的
int q = position[col];//存放的数字大于0
B->data[q].row = A->data[p].col;
B->data[q].col = A->data[p].row;
B->data[q].e = A->data[p].e;
position[col]++;
}
}
int main()
{
int m = 0;
ElementType array[4][4] = { 0 };
Triple *p;
p = (Triple*)malloc(sizeof(Triple));
TSMatrix *L;
L = (TSMatrix*)malloc(sizeof(TSMatrix));
TSMatrix *M;
M = (TSMatrix*)malloc(sizeof(TSMatrix));
printf("请输入二维数组的值\n");
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
scanf_s("%d", &array[i][j]);
}
}
//对于三元组的操作
for (int i = 0; i < 4; i++)
{
for (int j = 0; j < 4; j++)
{
if (array[i][j] != 0)//找到后就赋值到三元组里面
{
L->data[m].row = i+1;
L->data[m].col = j+1;
L->data[m].e = array[i][j];
m++;
}
}
}
//打印出三元组看看
L->len = m;
printf("%d\n", m);
printf("三元存储的效果如下\n");
printf("row col e\n");
for (int i = 0; i < m; i++)
{
printf("%d %d %d", L->data[i].row, L->data[i].col, L->data[i].e);
printf("\n");
}
printf("转置后的三元组为\n");
FastTranse(L, M);
for (int i = 1; i <= M->len; i++)
{
printf("%d %d %d", M->data[i].row, M->data[i].col, M->data[i].e);
printf("\n");
}
system("pause");
getchar();
return 0;
}
C-稀疏矩阵一次快速定位算法-数据结构
最新推荐文章于 2023-02-26 14:10:37 发布