codeforces 1520c Not Adjacent Matrix

题目如下
We will consider the numbers 𝑎 and 𝑏 as adjacent if they differ by exactly one, that is, |𝑎−𝑏|=1.

We will consider cells of a square matrix 𝑛×𝑛 as adjacent if they have a common side, that is, for cell (𝑟,𝑐) cells (𝑟,𝑐−1), (𝑟,𝑐+1), (𝑟−1,𝑐) and (𝑟+1,𝑐) are adjacent to it.

For a given number 𝑛, construct a square matrix 𝑛×𝑛 such that:

Each integer from 1 to 𝑛2 occurs in this matrix exactly once;
If (𝑟1,𝑐1) and (𝑟2,𝑐2) are adjacent cells, then the numbers written in them must not be adjacent.
Input
The first line contains one integer 𝑡 (1≤𝑡≤100). Then 𝑡 test cases follow.

Each test case is characterized by one integer 𝑛 (1≤𝑛≤100).

Output
For each test case, output:

-1, if the required matrix does not exist;
the required matrix, otherwise (any such matrix if many of them exist).
The matrix should be outputted as 𝑛 lines, where each line contains 𝑛 integers.

题目大意
在nn的方格中,填入1到nn共n2个数,要求构造每个方格中的数与上下左右的数在原自然数组中均不相临近,若可以构造就输出这个n宫格;否则,就输出-1。

解题思路
大概就是打乱顺序,保证每个格子上下左右的相邻格中没有相邻自然数。
在n*n的方格中,只有当n为2时,一定会出现相邻格子中出现相邻自然数,所以排除单独列出n为2时的情况即可。
不能按照自然数的顺序,那么我们将奇偶数分开填入格子来实现相邻格子中没有相邻自然数。
实现
注意偶数开始填入的位置

点击查看代码
int o = 1;
    //先输入n*n/2个奇数for
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(o <= n * n){ //填入正确个数的奇数
                nums[i][j] = o;
                o += 2;
            }
        }
    }
    int e = 2;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(!nums[i][j]){ //接着奇数填完开始填偶数
                nums[i][j] = e;
                e += 2;
            }
        }
    }

注意二维数组的初始化

点击查看代码
memset(nums, 0, sizeof(nums));

完整代码如

点击查看代码
#include <stdio.h>
#include <string.h>

void arr(int n){
    int nums[n][n];
    memset(nums, 0, sizeof(nums));
    int o = 1;
    //先输入n*n/2个奇数for
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(o <= n * n){ //填入正确个数的奇数
                nums[i][j] = o;
                o += 2;
            }
        }
    }
    int e = 2;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            if(!nums[i][j]){ //接着奇数填完开始填偶数
                nums[i][j] = e;
                e += 2;
            }
        }
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            printf("%d ",nums[i][j]);
        }
        printf("\n");
    }
}

int main(){
    int t;
    scanf("%d",&t);
    while(t--){
        int n;
        scanf("%d",&n);
        if(n == 2){
            printf("-1\n");
            continue;
        }else{
            arr(n);
            }
        }
    return 0;
}
posted @ 2025-06-30 21:55  sirro1uta  阅读(24)  评论(0)    收藏  举报