请用c语言帮我写一个代码:从键盘输入矩阵的行、列和非零元素个数,以及若干组数据(分别表示系数矩阵非零元素的行、列和值),即三元组表对应的信息;为了便于观察结果,请将新三元组表中的每条记录均初值化为0,再开始完成矩阵的快速转置
时间: 2024-05-06 07:22:14 浏览: 36
Matrix-keyboard,c语言扑克牌怎么写源码,c语言程序
```
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int row;
int col;
int value;
} Triple;
void printMatrix(Triple *matrix, int m, int n) {
int p = 1;
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
if (matrix[p].row == i && matrix[p].col == j) {
printf("%d ", matrix[p].value);
p++;
} else {
printf("0 ");
}
}
printf("\n");
}
}
void transpose(Triple *matrix, Triple *result, int m, int n, int count) {
int *rowSize = (int*)calloc(n + 1, sizeof(int));
int *rowStart = (int*)calloc(n + 1, sizeof(int));
for (int i = 1; i <= count; i++) {
rowSize[matrix[i].col]++;
}
rowStart[1] = 1;
for (int i = 2; i <= n; i++) {
rowStart[i] = rowStart[i - 1] + rowSize[i - 1];
}
for (int i = 1; i <= count; i++) {
int j = rowStart[matrix[i].col]++;
result[j].row = matrix[i].col;
result[j].col = matrix[i].row;
result[j].value = matrix[i].value;
}
free(rowSize);
free(rowStart);
}
int main() {
int m, n, count;
printf("Enter the size of matrix (m n count): ");
scanf("%d%d%d", &m, &n, &count);
Triple *matrix = (Triple*)calloc(count + 1, sizeof(Triple));
for (int i = 1; i <= count; i++) {
printf("Enter the %d-th element (row col value): ", i);
scanf("%d%d%d", &matrix[i].row, &matrix[i].col, &matrix[i].value);
}
printf("Original matrix:\n");
printMatrix(matrix, m, n);
Triple *result = (Triple*)calloc(count + 1, sizeof(Triple));
transpose(matrix, result, m, n, count);
printf("Transposed matrix:\n");
printMatrix(result, n, m);
free(matrix);
free(result);
return 0;
}
```
阅读全文