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 语言中的探索
Java方法栈日志的艺术:从错误定位到性能优化的深度指南
https://www.shuihudhg.cn/133725.html
PHP 获取本机端口的全面指南:实践与技巧
https://www.shuihudhg.cn/133724.html
Python内置函数:从核心原理到高级应用,精通Python编程的基石
https://www.shuihudhg.cn/133723.html
Java Stream转数组:从基础到高级,掌握高性能数据转换的艺术
https://www.shuihudhg.cn/133722.html
深入解析:基于Java数组构建简易ATM机系统,从原理到代码实践
https://www.shuihudhg.cn/133721.html
热门文章
C 语言中实现正序输出
https://www.shuihudhg.cn/2788.html
c语言选择排序算法详解
https://www.shuihudhg.cn/45804.html
C 语言函数:定义与声明
https://www.shuihudhg.cn/5703.html
C语言中的开方函数:sqrt()
https://www.shuihudhg.cn/347.html
C 语言中字符串输出的全面指南
https://www.shuihudhg.cn/4366.html