title: 稀疏矩阵转置
date: 2020-10-30 14:38:52
tags: 稀疏矩阵转置
categories: 数据结构
#include <stdio.h>
#define MAX_LENGTH 100
// 定义一个用来表示非零元素的结构体
typedef struct a
{
// 非零元素的行下标
int rowIndex;
// 非零元素的列下标
int colIndex;
// 非零元素的值
int number;
} NotZeroMember;
// 定义一个表示矩阵的结构体
typedef struct b
{
// 开一个数组用于存储非零元素
NotZeroMember array[MAX_LENGTH];
// 数组长度 即该矩阵中非零元素的个数
int arrayLength;
// 矩阵的行数和列数
int rows, cols;
} Matrix;
int main(void)
{
// 开一个稀疏矩阵
int arr[5][7] = {0, 0, 3, 0, 0, 0, 6,
0, 0, 0, 7, 5, 0, 0,
0, 0, 0, 0, 0, 0, 0,
0, 9, 0, 0, 6, 0, 0,
1, 0, 0, 0, 0, 0, 8};
// 将稀疏矩阵压缩
Matrix matrix;
matrix.rows = 5;
matrix.cols = 7;
matrix.arrayLength = 0;
for (int i = 0; i < 5; i++)
for (int j = 0; j < 7; j++)
{
if (arr[i][j] != 0)
{
// 行
matrix.array[++matrix.arrayLength].rowIndex = i + 1;
// 列
matrix.array[matrix.arrayLength].colIndex = j + 1;
matrix.array[matrix.arrayLength].number = arr[i][j];
}
}
for (int i = 1; i <= matrix.arrayLength; i++)
printf("%d行 %d列 元素值:%d\n", matrix.array[i].rowIndex,
matrix.array[i].colIndex, matrix.array[i].number);
// 开始转置矩阵
// num数组用于记录原矩阵每列有几个非0元素
// num数组中对应的下标就是对应的列序号
int num[matrix.cols + 1] = {0};
for (int i = 1; i <= matrix.arrayLength; i++)
num[matrix.array[i].colIndex]++;
for (int i = 1; i <= matrix.cols; i++)
printf("第 %d 列有 %d 个非零元素\n", i, num[i]);
// location 数组用于记录转置前每列的首个非零元素(即转置后每行的首个非0元素)
// 在转置以后的被压缩以后的数组里的下标
int location[matrix.cols + 1] = {0, 1};
for (int i = 2; i <= matrix.cols; i++)
location[i] = location[i - 1] + num[i - 1];
printf("location数组:\n");
for (int i = 1; i <= matrix.cols; i++)
printf("%d ", location[i]);
printf("\n");
// 数组转置
Matrix comperssedMatrix;
comperssedMatrix.cols = matrix.rows;
comperssedMatrix.rows = matrix.cols;
comperssedMatrix.arrayLength = matrix.arrayLength;
for (int i = 1; i <= matrix.arrayLength; i++)
{
int t = location[matrix.array[i].colIndex];
comperssedMatrix.array[t].number = matrix.array[i].number;
comperssedMatrix.array[t].colIndex = matrix.array[i].rowIndex;
comperssedMatrix.array[t].rowIndex = matrix.array[i].colIndex;
location[matrix.array[i].colIndex]++;
}
for (int i = 1; i <= comperssedMatrix.arrayLength; i++)
printf("%d行 %d列 元素值:%d\n", comperssedMatrix.array[i].rowIndex,
comperssedMatrix.array[i].colIndex, comperssedMatrix.array[i].number);
int index = 1;
// 打印原来的数组
for (int i = 0; i < 5; i++)
{
for (int j = 0; j < 7; j++)
printf("%d ", arr[i][j]);
printf("\n");
}
printf("================\n");
printf("-----转置后-----\n");
printf("================\n");
// 打印转置后的数组
for (int i = 1; i <= comperssedMatrix.rows; i++)
{
for (int j = 1; j <= comperssedMatrix.cols; j++)
{
if(i == comperssedMatrix.array[index].rowIndex && j == comperssedMatrix.array[index].rowIndex)
{
printf("%d ", comperssedMatrix.array[index].number);
index++;
}
else
printf("0 ");
}
printf("\n");
}
return 0;
}