稀疏矩阵表示为三元组c语言
时间: 2024-06-14 18:05:31 浏览: 19
稀疏矩阵可以使用三元组顺序表来表示,下面是一个用C语言表示稀疏矩阵的示例:
```c
#include <stdio.h>
#define MAX_SIZE 100
typedef struct {
int row;
int col;
int value;
} Triple;
typedef struct {
Triple data[MAX_SIZE];
int rows;
int cols;
int nums;
} SparseMatrix;
void createSparseMatrix(SparseMatrix *matrix) {
printf("Enter the number of rows: ");
scanf("%d", &matrix->rows);
printf("Enter the number of columns: ");
scanf("%d", &matrix->cols);
printf("Enter the number of non-zero elements: ");
scanf("%d", &matrix->nums);
printf("Enter the elements in the format (row, column, value):\n");
for (int i = 0; i < matrix->nums; i++) {
scanf("%d %d %d", &matrix->data[i].row, &matrix->data[i].col, &matrix->data[i].value);
}
}
void displaySparseMatrix(SparseMatrix matrix) {
printf("Sparse Matrix:\n");
for (int i = 0; i < matrix.nums; i++) {
printf("(%d, %d, %d)\n", matrix.data[i].row, matrix.data[i].col, matrix.data[i].value);
}
}
int main() {
SparseMatrix matrix;
createSparseMatrix(&matrix);
displaySparseMatrix(matrix);
return 0;
}
```
这段代码定义了两个结构体,`Triple`用于表示稀疏矩阵的非零元素,`SparseMatrix`用于表示稀疏矩阵本身。`createSparseMatrix`函数用于创建稀疏矩阵,`displaySparseMatrix`函数用于显示稀疏矩阵的内容。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_lunwen.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)