The meaning of the question: color the edges of the n*n grid graph with k colors, each color has the same number of edges, and the structure does not have the same color circle and the entire row and column of different colors.
Solution: Thinking of
n=1, k=1, 2 * (n + 1) * n% k != 0 These three situations are definitely not acceptable.
Next consider two cases.
①n% k != 0
This is just one line by line and the color is painted from 1 to k along the line, and then connected to the column.
②n% k = 0
if coated as described above, the ring will be the same color, this coating we:
if n = 3, k = 3, for the row it
. 1 2. 3
2. 3. 1
. 3. 1 2
i.e. at the beginning of each coating color to Move one back.
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<set>
#include<map>
#include<sstream>
#include<iomanip>
#define ll long long
using namespace std;
int t, n, k;
int main() {
scanf("%d", &t);
while (t--) {
scanf("%d%d", &n, &k);
if (n == 1 || k == 1 || (2 * (n + 1) * n) % k != 0) puts("-1");
else {
if (n % k != 0) {
int x = 1;
for (int i = 1; i <= n + 1; i++) {
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
for (int i = 1; i <= n + 1; i++) {
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
}
else {
int x = 1;
for (int i = 1; i <= n + 1; i++) {
x = (i - 1) % k + 1;
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
for (int i = 1; i <= n + 1; i++) {
x = (i - 1) % k + 1;
for (int j = 1; j <= n; j++) {
printf("%d ", (x - 1) % k + 1);
++x;
}
puts("");
}
}
}
}
return 0;
}