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:
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:
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;
}
Codeforces Round #719 (Div. 3) C. Not Adjacent Matrix(构造)
原文:https://www.cnblogs.com/lipoicyclic/p/14736492.html