#54313: C++


shiaoann (一孝 21)


#include <bits/stdc++.h>

using namespace std;

int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int T;
    cin >> T;
    while (T--) {
        int N, M;
        cin >> N >> M;

        vector < vector < int >> mat(N, vector < int > (N, 0));

        int num = 1, total = N * N;
        int top = 0, bottom = N - 1, left = 0, right = N - 1;

        if (M == 1) { // 順時針
            while (num <= total) {
                // 右
                for (int j = left; j <= right && num <= total; j++)
                    mat[top][j] = num++;
                top++;

                // 下
                for (int i = top; i <= bottom && num <= total; i++)
                    mat[i][right] = num++;
                right--;

                // 左
                for (int j = right; j >= left && num <= total; j--)
                    mat[bottom][j] = num++;
                bottom--;

                // 上
                for (int i = bottom; i >= top && num <= total; i--)
                    mat[i][left] = num++;
                left++;
            }
        } else { // M == 2, 逆時針
            while (num <= total) {
                // 下
                for (int i = top; i <= bottom && num <= total; i++)
                    mat[i][left] = num++;
                left++;

                // 右
                for (int j = left; j <= right && num <= total; j++)
                    mat[bottom][j] = num++;
                bottom--;

                // 上
                for (int i = bottom; i >= top && num <= total; i--)
                    mat[i][right] = num++;
                right--;

                // 左
                for (int j = right; j >= left && num <= total; j--)
                    mat[top][j] = num++;
                top++;
            }
        }

        // 輸出,每個數字寬度為 5
        for (int i = 0; i < N; i++) {
            for (int j = 0; j < N; j++) {
                cout << setw(5) << mat[i][j];
            }
            cout << "\n";
        }
        cout << "\n"; // 每組一空行
    }
    return 0;
}