C 语言中矩阵旋转的实现224


矩阵旋转是一种操作,它将矩阵中的元素按照顺时针或逆时针方向移动。在编程中,执行矩阵旋转是一个常见的任务,尤其是在图像处理和线性代数等领域。

在 C 语言中,我们可以使用指针和数组来实现矩阵旋转。以下是一个实现矩阵旋转的函数:```c
#include
#include
// 顺时针旋转矩阵
void rotateClockwise(int matrix, int n) {
// 申请临时空间来存储旋转后的矩阵
int rotated = malloc(n * sizeof(int *));
for (int i = 0; i < n; ++i) {
rotated[i] = malloc(n * sizeof(int));
}
// 旋转矩阵
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
rotated[j][n - 1 - i] = matrix[i][j];
}
}
// 释放原矩阵的空间
for (int i = 0; i < n; ++i) {
free(matrix[i]);
}
free(matrix);
// 赋值旋转后的矩阵
matrix = rotated;
}
// 逆时针旋转矩阵
void rotateCounterClockwise(int matrix, int n) {
// 申请临时空间来存储旋转后的矩阵
int rotated = malloc(n * sizeof(int *));
for (int i = 0; i < n; ++i) {
rotated[i] = malloc(n * sizeof(int));
}
// 旋转矩阵
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
rotated[n - 1 - j][i] = matrix[i][j];
}
}
// 释放原矩阵的空间
for (int i = 0; i < n; ++i) {
free(matrix[i]);
}
free(matrix);
// 赋值旋转后的矩阵
matrix = rotated;
}
// 打印矩阵
void printMatrix(int matrix, int n) {
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
printf("%d ", matrix[i][j]);
}
printf("");
}
}
int main() {
int n;
printf("Enter the size of the matrix: ");
scanf("%d", &n);

int matrix = malloc(n * sizeof(int *));
for (int i = 0; i < n; ++i) {
matrix[i] = malloc(n * sizeof(int));
}

printf("Enter the elements of the matrix:");
for (int i = 0; i < n; ++i) {
for (int j = 0; j < n; ++j) {
scanf("%d", &matrix[i][j]);
}
}
int choice;
printf("1. Rotate clockwise2. Rotate counterclockwiseEnter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
rotateClockwise(matrix, n);
break;
case 2:
rotateCounterClockwise(matrix, n);
break;
default:
printf("Invalid choice");
}
printf("Rotated matrix:");
printMatrix(matrix, n);
return 0;
}
```

在 main 函数中,用户可以选择顺时针或逆时针旋转矩阵。然后,该程序调用相应的旋转函数来执行旋转操作并打印旋转后的矩阵。

这个程序的时间复杂度是 O(n^2),其中 n 是矩阵的大小,因为我们需要遍历矩阵中的每个元素一次来执行旋转操作。

以下是程序运行时的示例:```
Enter the size of the matrix: 3
Enter the elements of the matrix:
1 2 3
4 5 6
7 8 9
1. Rotate clockwise
2. Rotate counterclockwise
Enter your choice: 1
Rotated matrix:
7 4 1
8 5 2
9 6 3
```

2024-11-23


上一篇:用 C 语言绘制爱心图案

下一篇:字符输出在 C 语言中的探索