1. 程式人生 > >稀疏矩陣的三元組表儲存 C語言

稀疏矩陣的三元組表儲存 C語言

#include <stdio.h>

#define MaxSize	100
typedef int	DataType;

typedef struct {
	DataType	v;
	int			i, j;
}TriTupleNode;

typedef struct {
	TriTupleNode	data[MaxSize];	//三元組陣列
	int	m, n, t;	//行數 列數以及非零元個數
}TriTupleTable;


void CreateTriTupleTable(TriTupleTable *T)
{
	//int m, n, t;
	int i;
	printf("輸入行數,列數以及非零元的個數:");
	scanf("%d%d%d", &T->m, &T->n, &T->t);
	
	for (i=1; i<=T->t; ++i)
	{
		printf("請輸入第%d個頂點的行號列號以及值", i);
		scanf("%d%d%d", &T->data[i].i, &T->data[i].j, &T->data[i].v);
	}
}

void Traverse(TriTupleTable *T)
{
	int i;
	printf("%d  %d  %d\n", T->m, T->n, T->t);

	for (i=1;  i<=T->t; ++i)
	{
		printf("%d  %d  %d\n", T->data[i].i, T->data[i].j, T->data[i].v);
	}
}

void TransMatrix(TriTupleTable *A, TriTupleTable*B)
{
	int p, q, col;
	B->m = A->n;
	B->n = A->m;
	B->t = A->t;
	if (0 == B->t)
		return ;
	q = 0;
	for (col=0; col<A->n; ++col)
		for (p=0; p<A->t; ++p)
		{
			if (A->data[p].j == col)
			{
				B->data[q].i = A->data[p].j;
				B->data[q].j = A->data[p].i;
				B->data[q].v = A->data[p].v;
				++q;
			}
		}
}
int main(void)
{
	TriTupleTable A, B;
	CreateTriTupleTable(&A);
	Traverse(&A);
	TransMatrix(&A, &B);
	Traverse(&B);
	return 0;
}