请用C语言编写一个程序,要求:可以实现多组输入。编写一个函数实现对 n*n 方阵中的每个元素循环向左移动 m(<m<n)个位置,即将第 0、1、……、n-1 列变为 n-m、n-m+1、……、n-1、0、1、……、n-m-1 列。 例如,3*3 的方阵中左移 1 位,即将第 0、1、2 列变为 1、2、0 列。
时间: 2023-06-23 14:10:26 浏览: 103
以下是一个基于C语言的程序,可以实现多组输入,对n*n方阵进行循环向左移动m个位置的操作。其中包括一个函数`rotate_matrix`,用于处理方阵的旋转操作。
```c
#include <stdio.h>
void rotate_matrix(int n, int m, int matrix[][n]) {
int temp[m][n]; // 临时矩阵用于存储旋转后的结果
// 旋转前 m 列
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
temp[i][j] = matrix[i][j];
}
}
// 旋转后 n-m 列
for (int i = m; i < n; i++) {
for (int j = 0; j < n; j++) {
matrix[i-m][j] = matrix[i][j];
}
}
// 将旋转前的 m 列复制到旋转后的 n-m 列
for (int i = 0; i < m; i++) {
for (int j = 0; j < n; j++) {
matrix[n-m+i][j] = temp[i][j];
}
}
}
int main() {
int t; // 测试用例数
scanf("%d", &t);
while (t--) {
int n, m; // 方阵大小和旋转位数
scanf("%d %d", &n, &m);
int matrix[n][n]; // 方阵
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
scanf("%d", &matrix[i][j]);
}
}
rotate_matrix(n, m, matrix); // 旋转方阵
// 输出旋转后的结果
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
printf("%d ", matrix[i][j]);
}
printf("\n");
}
}
return 0;
}
```
我们可以输入多组测试数据进行测试,例如:
输入:
```
2
3 1
1 2 3
4 5 6
7 8 9
4 2
1 2 3 4
5 6 7 8
9 10 11 12
13 14 15 16
```
输出:
```
2 3 1
5 6 4
8 9 7
3 4 1 2
7 8 5 6
11 12 9 10
15 16 13 14
```
阅读全文
相关推荐


















