第十六届蓝桥杯青少组C++省赛[2025.8.9]第二部分编程题(4、矩阵圈层交错旋转)

发布于:2025-08-16 ⋅ 阅读:(18) ⋅ 点赞:(0)

参考程序:

#include <bits/stdc++.h>
using namespace std;

const int MAXN = 105;
int a[MAXN][MAXN];

int main() {
    

    int n;
    if (!(cin >> n)) return 0;

    for (int i = 0; i < n; ++i)
        for (int j = 0; j < n; ++j)
            cin >> a[i][j];

    int layers = n / 2; // 每次处理一圈,外层到里层共有 floor(n/2) 层

    // 对每一层做 (right-left) 次四元循环替换
    for (int layer = 0; layer < layers; ++layer) {
        int top = layer;
        int left = layer;
        int bottom = n - 1 - layer;
        int right = n - 1 - layer;

        // 对当前圈上的每一个偏移 i 做一次 4 格循环替换
        for (int i = 0; i < right - left; ++i) {
            int rTop = top,        cTop = left + i;
            int rRight = top + i,  cRight = right;
            int rBottom = bottom,  cBottom = right - i;
            int rLeft = bottom - i, cLeft = left;

            if (layer % 2 == 0) {
                // 顺时针 90° (CW):左 -> 上, 下 -> 左, 右 -> 下, 上 -> 右
                int tmp = a[rLeft][cLeft];
                a[rLeft][cLeft]     = a[rBottom][cBottom];
                a[rBottom][cBottom] = a[rRight][cRight];
                a[rRight][cRight]   = a[rTop][cTop];
                a[rTop][cTop]       = tmp;
            } else {
                // 逆时针 90° (CCW):上 -> 左, 右 -> 上, 下 -> 右, 左 -> 下
                int tmp = a[rTop][cTop];
                a[rTop][cTop]       = a[rRight][cRight];
                a[rRight][cRight]   = a[rBottom][cBottom];
                a[rBottom][cBottom] = a[rLeft][cLeft];
                a[rLeft][cLeft]     = tmp;
            }
        }
    }

    // 输出结果
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < n; ++j) {
            if (j) cout << ' ';
            cout << a[i][j];
        }
        cout << '\n';
    }

    return 0;
}


网站公告

今日签到

点亮在社区的每一天
去签到