1 solutions

  • 0
    @ 2022-3-21 23:30:32

    要让相邻单元格的差值不为1,能构造输出,不能就直接-1。 用奇数和奇数相邻,偶数和偶数相邻。 可以先从小到大填充所有的奇数,填完奇数之后再从小到大填充完所有的偶数。 这种做法除了n = 2 n = 2n=2 不满足情况应当输出-1外,其他的均可满足。

    #include<bits/stdc++.h>
    using namespace std;
    const int N = 200;
    int ma[N][N];
    int main() {
        std::ios::sync_with_stdio(false);
        int t;
        cin >> t;
        while (t--) {
            int n;
            cin >> n;
            if (n == 2) {
                cout << -1 << endl;
                continue;
            }
            int cnt = n * n;
            int x = 1;
            for (int j = 0; j < n; j++) {
                for (int k = 0; k < n; k++) {
                    cout << x << " ";
                    if (x + 2 > cnt&&cnt>=2) x = 2;
                    else x += 2;
                }
                cout<<endl;
            }
        }
    }
    

    Information

    ID
    5901
    Time
    4000ms
    Memory
    256MiB
    Difficulty
    9
    Tags
    # Submissions
    10
    Accepted
    6
    Uploaded By