For a square matrix of integers of size 𝑛×𝑛n×n, let's define its beauty as follows: for each pair of side-adjacent elements 𝑥and 𝑦, write out the number |x−y|, and then find the number of different numbers among them.
For example, for the matrix (1342) the numbers we consider are |1−3|=2, |1−4|=3, |3−2|=1 and |4−2|=2; there are 3 different numbers among them (2, 3 and 1), which means that its beauty is equal to 3.
You are given an integer 𝑛n. You have to find a matrix of size 𝑛×𝑛n×n, where each integer from 1 to n2 occurs exactly once, such that its beauty is the maximum possible among all such matrices.
Input
The first line contains a single integer 𝑡t (1≤t≤49) – the number of test cases.
The first (and only) line of each test case contains a single integer 𝑛n (2≤n≤50).
Output
For each test case, print 𝑛n rows of 𝑛n integers — a matrix of integers of size 𝑛×𝑛n×n, where each number from 1 to 𝑛2 occurs exactly once, such that its beauty is the maximum possible among all such matrices. If there are multiple answers, print any of them.
Example
input
Copy
2
2
3
output
Copy
1 3 4 2 1 3 4 9 2 7 5 8 6
就是数学规律,测试样例没有规律,把答案代码输出几组就明白了
#include<iostream>
#define ll long long
using namespace std;
ll n,t;
ll a[60][60];
int main(){
cin >> t;
while(t --){
cin >> n;
int xx = n * n;
int yy = 1;
for(int i = 1; i <= n; i ++){
if(i & 1){
for(int j = 1; j <= n ;j ++){
if(j & 1){
a[i][j] = yy ++;
}
else{
a[i][j] = xx --;
}
}
}
else{
for(int j = n; j >= 1 ;j --){
if(j & 1){
a[i][j] = xx --;
}
else{
a[i][j] = yy ++;
}
}
}
}
for(int i = 1; i <= n; i ++){
for(int j = 1; j <= n;j ++)
cout << a[i][j] << " ";
cout << endl;
}
}
}