Loading

Codeforces Round #719 (Div. 3) C. Not Adjacent Matrix(构造)

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

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

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

  • Each integer from 11 to 𝑛2n2 occurs in this matrix exactly once;
  • If (𝑟1,𝑐1)(r1,c1) and (𝑟2,𝑐2)(r2,c2) are adjacent cells, then the numbers written in them must not be adjacent.

Input

The first line contains one integer 𝑡t (1≤𝑡≤1001≤t≤100). Then 𝑡t test cases follow.

Each test case is characterized by one integer 𝑛n (1≤𝑛≤1001≤n≤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 𝑛n lines, where each line contains 𝑛n integers.

Example

input

Copy

3
1
2
3

output

Copy

1
-1
2 9 7
4 6 3
1 8 5

考虑进行如下构造:

for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				int now = i + (j - 1) * n;
				int nx = i, ny = (i + (j - 1));
				if(ny > n) ny = (ny % (n + 1) + 1);
				m[nx][ny] = now;
			}
		}

即:

1 5 9
 2 6 10
  3 7 11
   4 8 12...

越界的话模一下。这样能保证相差1的一定在斜对角线。注意构造完后遍历一遍判断是否有非法情况,有的话(其实只有n = 2是不可行的)则输出-1.

#include <bits/stdc++.h>
using namespace std;
int n;
int m[105][105];
int d[4][2] = {{0,1}, {0, -1}, {1, 0}, {1, 0}};
bool check(int x, int y) {
	for(int i = 0; i < 4; i++) {
		int nx = x + d[i][0], ny = y + d[i][1];
		if(m[nx][ny] == 0) continue;
		if(abs(m[x][y] - m[nx][ny]) == 1) return 0;
	}
	return 1;
}
int main() {
	int t;
	cin >> t;
	while(t--) {
		cin >> n;
		memset(m, 0, sizeof(m));
		bool flag = 1;
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				int now = i + (j - 1) * n;
				int nx = i, ny = (i + (j - 1));
				if(ny > n) ny = (ny % (n + 1) + 1);
				m[nx][ny] = now;
			}
		}
		for(int i = 1; i <= n; i++) {
			for(int j = 1; j <= n; j++) {
				if(!check(i, j)) {
					flag = 0;
					break;
				}
			}
		}
		if(flag) {
			for(int i = 1; i <= n; i++) {
				for(int j = 1; j <= n; j++) {
					cout << m[i][j] << " ";
				}
				cout << endl;
			}
		} else cout << -1 << endl;
	}
	return 0;
}

posted @ 2021-05-06 19:06  脂环  阅读(115)  评论(0编辑  收藏  举报