题解 | #矩阵交换#指针解法,主要是字符输入容易出错

矩阵交换

https://www.nowcoder.com/practice/ec44d4ff8c794b2f9205bdddbde96817?tpId=290&tqId=618637&ru=%2Fpractice%2F351b3d03e410496ab5a407b7ca3fd841&qru=%2Fta%2Fbeginner-programmers%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj

#include <stdio.h>
#include <stdlib.h>

void SwapR(int** a, int x, int y, int m) {
    int* temp = a[x];
    a[x] = a[y];
    a[y] = temp;
}

void SwapC(int** a, int x, int y, int n) {
    for (int i = 0; i < n; i++) {
        int temp = a[i][x];
        a[i][x] = a[i][y];
        a[i][y] = temp;
    }
}

int main() {
    int n, m, b, x, y;
    char c;
    scanf("%d %d", &n, &m);
    int** a = (int**)malloc(n * sizeof(int*));
    for (int i = 0; i < n; i++) {
        a[i] = (int*)malloc(m * sizeof(int));
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            scanf("%d ", &a[i][j]);
        }
    }
    scanf("%d ", &b);
    for (int i = 0; i < b; i++) {
        scanf(" %c %d %d", &c, &x, &y);
        if (c == 'r') {
            SwapR(a, --x, --y, m);
        } else if (c == 'c') {
            SwapC(a, --x, --y, n);
        }
    }
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < m; j++) {
            printf("%d ", a[i][j]);
        }
        printf("\n");
    }
    for (int i = 0; i < n; i++) {
        free(a[i]);
    }
    free(a);
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务