题解 | #矩阵交换#
矩阵交换
https://www.nowcoder.com/practice/ec44d4ff8c794b2f9205bdddbde96817
#include <stdio.h> //BC108 矩阵交换 int main() { //定义矩阵大小 int n = 0; int m = 0; scanf("%d %d", &n, &m); //矩阵赋值 int i = 0; int j = 0; int arr[n][m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { scanf("%d", &arr[i][j]); } } //输入进行变幻的次数 int k = 0; scanf("%d", &k); //分三种情况进行操作 int a = 0;//a仅仅是用来循环次数 while (a < k) { //先定义要执行的操作 char ope = 0; //定义具体位置 int x = 0; int y = 0; while (getchar() != '\n');//清理缓冲区 scanf("%c %d %d", &ope, &x, &y); switch (ope) { case 'r'://行操作,只需关心列 for (j = 0; j < m; j++) { //一定要注意是x-1,y-1你的具体行数和数组下标差1 int temp = arr[x-1][j]; arr[x-1][j] = arr[y-1][j]; arr[y-1][j] = temp; } break; case 'c'://列操作,只需关心行 for (i = 0; i < n; i++) { int temp = arr[i][x-1]; arr[i][x-1] = arr[i][y-1]; arr[i][y-1] = temp; } break; default://不进行操作 break; } a++; } //输出变换后的矩阵 for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%d ", arr[i][j]); } printf("\n"); } return 0; }