#include<stdio.h>
typedef struct{
int data[100][100];
int m, n;
}matrix;
typedef int spmatrix[100][3];
void compressmatrix(matrix A, spmatrix B)//二维数组转为三元组表示
{
int i, j, k = 1;
for(i=0;i<A.m;i++)
for(j=0;j<A.n;j++)
if (A.data[i][j] != 0)
{
B[k][0] = i;
B[k][1] = j;
B[k][2] = A.data[i][j];
k++;
}
B[0][0] = A.m;
B[0][1] = A.n;
B[0][2] = k-1;
}
void transpmatrix(spmatrix B, spmatrix C)//三元组形式的矩阵转置
{
int i, j, t, m, n;
int x[100];
int y[100];
m = B[0][0], n = B[0][1], t = B[0][2];
C[0][0] = n, C[0][1] = m, C[0][2] = t;
if (t > 0)
{
for (i = 0; i < n+1; i++)
x[i] = 0; //初始化n 个,原来的列,现在的行。
for (i = 1; i <= t; i++)
x[B[i][1]+1] += 1; //此处功能:记录现在每一行有几个元素
y[0] = 1;
for (i = 1; i <= n; i++)
y[i] = y[i - 1] + x[i - 1];//实际对应位置,累加的效果。
for (i = 1; i <= t; i++)
{
j = y[B[i][1]+1];//j的结果为这一行现在应该存放的位置
C[j][0] = B[i][1];//列换行
C[j][1] = B[i][0];//行换列
C[j][2] = B[i][2];//值不变
++y[B[i][1]+1];//此位置存放后要后移一位
}
}
}
void display(spmatrix D)
{
int i,j;
for (i = 0; i <= D[0][2]; i++)
printf("序号:%d,一列:%d,二列:%d,三:%d\n",i, D[i][0], D[i][1], D[i][2]);
}
void main()
{
int b=1;
matrix A;
int i, j;
for (i = 0; i < 6; i++)
for (j = 0; j < 7; j++)
A.data[i][j] = 0;
A.m = 6;
A.n = 7;
A.data[2][0] = -5;
A.data[4][0] = 1;
A.data[3][1] = 2;
A.data[0][2] = 13;
A.data[0][4] = 12;
A.data[5][5] = 4;
A.data[2][6] = 21;
spmatrix B, C;
compressmatrix(A, B);
display(B);
transpmatrix(B, C);
printf("---------分割线,以下为转置后的内容。--------\n");
display(C);
}
typedef struct{
int data[100][100];
int m, n;
}matrix;
typedef int spmatrix[100][3];
void compressmatrix(matrix A, spmatrix B)//二维数组转为三元组表示
{
int i, j, k = 1;
for(i=0;i<A.m;i++)
for(j=0;j<A.n;j++)
if (A.data[i][j] != 0)
{
B[k][0] = i;
B[k][1] = j;
B[k][2] = A.data[i][j];
k++;
}
B[0][0] = A.m;
B[0][1] = A.n;
B[0][2] = k-1;
}
void transpmatrix(spmatrix B, spmatrix C)//三元组形式的矩阵转置
{
int i, j, t, m, n;
int x[100];
int y[100];
m = B[0][0], n = B[0][1], t = B[0][2];
C[0][0] = n, C[0][1] = m, C[0][2] = t;
if (t > 0)
{
for (i = 0; i < n+1; i++)
x[i] = 0; //初始化n 个,原来的列,现在的行。
for (i = 1; i <= t; i++)
x[B[i][1]+1] += 1; //此处功能:记录现在每一行有几个元素
y[0] = 1;
for (i = 1; i <= n; i++)
y[i] = y[i - 1] + x[i - 1];//实际对应位置,累加的效果。
for (i = 1; i <= t; i++)
{
j = y[B[i][1]+1];//j的结果为这一行现在应该存放的位置
C[j][0] = B[i][1];//列换行
C[j][1] = B[i][0];//行换列
C[j][2] = B[i][2];//值不变
++y[B[i][1]+1];//此位置存放后要后移一位
}
}
}
void display(spmatrix D)
{
int i,j;
for (i = 0; i <= D[0][2]; i++)
printf("序号:%d,一列:%d,二列:%d,三:%d\n",i, D[i][0], D[i][1], D[i][2]);
}
void main()
{
int b=1;
matrix A;
int i, j;
for (i = 0; i < 6; i++)
for (j = 0; j < 7; j++)
A.data[i][j] = 0;
A.m = 6;
A.n = 7;
A.data[2][0] = -5;
A.data[4][0] = 1;
A.data[3][1] = 2;
A.data[0][2] = 13;
A.data[0][4] = 12;
A.data[5][5] = 4;
A.data[2][6] = 21;
spmatrix B, C;
compressmatrix(A, B);
display(B);
transpmatrix(B, C);
printf("---------分割线,以下为转置后的内容。--------\n");
display(C);
}