#include <bits/stdc++.h>
#define rep(i, a, b) for (int i = a, i##_ = b; i < i##_; ++i)
using namespace std;
const int N = 2e3 + 5;
const pair<int, int> S[][4] = {
{{0, 0}, {0, 1}, {1, 1}, {2, 0}}, {{0, 0}, {0, 2}, {1, 1}, {1, 2}},
{{0, 0}, {1, -1}, {2, -1}, {2, 0}}, {{0, 0}, {0, 1}, {1, 0}, {1, 2}},
{{0, 0}, {0, 1}, {1, 0}, {2, 1}}, {{0, 0}, {0, 1}, {1, -1}, {1, 1}},
{{0, 0}, {1, 1}, {2, 0}, {2, 1}}, {{0, 0}, {0, 2}, {1, 0}, {1, 1}}};
const array<int, 4> Sub[] = {
// Sub[i] = {u, v, x, y}, T[i] = S[u] + Move(S[v], x, y)
{0, 6, 1, 0}, {3, 5, 0, 2},
{4, 7, 1, -1}, {4, 5, 1, 1}, {1, 2, 0, 1}, {7, 6, 0, 1},
{3, 1, 1, 1}, {0, 2, 1, 0}, {5, 7, 0, -2}, {4, 6, 1, 1},
};
int n, m, a[N][N];
void print() {
printf("%d\n", m);
rep(i, 0, n) rep(j, 0, n) printf("%d%c", a[i][j], " \n"[j == n - 1]);
}
const int ans9[][9] = {
{ 0, 1, 1, 2, 12, 12, 3, 13, 3},
{11, 1, 11, 12, 2, 12, 3, 3, 13},
{11, 11, 1, 2, 2, 4, 4, 13, 13},
{ 5, 15, 5, 6, 6, 4, 14, 4, 14},
{15, 5, 5, 16, 6, 7, 7, 14, 14},
{15, 15, 16, 6, 17, 7, 17, 8, 8},
{ 9, 9, 16, 16, 17, 17, 7, 8, 18},
{19, 9, 19, 10, 20, 10, 20, 18, 8},
{ 9, 19, 19, 10, 10, 20, 20, 18, 18},
};
void fS(int x, int y, int k) {
++m;
rep(i, 0, 4) a[x + S[k][i].first][y + S[k][i].second] = m;
}
void fT(int x, int y, int k) {
auto [u, v, dx, dy] = Sub[k];
fS(x, y, u), fS(x + dx, y + dy, v);
}
void Solve() {
scanf("%d", &n), m = 0;
rep(i, 0, n) fill(a[i], a[i] + n, 0);
switch (n % 2) {
case 0:
int k = n % 4;
rep(i, 0, n / 2) rep(j, 0, (n - k) / 4)
fT(i * 2, j * 4, 1);
if (k)
for (int i = 0, j = n - k; i < n - k; i += 4)
fT(i, j, 0);
break;
case 1:
if (n == 3) fT(0, 0, 3);
else if (n == 5 || n == 7) {
fS(0, 3, 0), fS(1, 0, 0), fS(1, 2, 4), fS(3, 1, 4), fS(3, 3, 5);
if (n == 7) fT(0, 5, 0), fT(5, 0, 1), fT(4, 5, 2);
}
if (n < 9) break;
int k = n % 4 - 1, t = (n - k - 9) / 2;
n -= k, m = 20;
rep(i, 0, 9) rep(j, 0, 9) a[t + i][j] = ans9[i][j];
for (int i = t - 2, r = t + 9; i >= 0; i -= 2, r += 2) {
int cnt = (t - i) / 2 + 1, c = cnt * 4;
rep(j, 0, cnt) fT(i, j * 4, 1), fT(r, j * 4, 1);
rep(k, 0, cnt) fT(i + 4 * k, c + 3, 0);
rep(k, 0, cnt - 1) fT(i + 3 + 4 * k, c + 1, 0);
fT(i, c, 5), fT(r - 2, c + 1, 7), fT(r - 1, c + 3, 2), fT(r - 4, c + 1, 6);
}
if (k) {
fT(n - 1, n, 2);
rep(i, 0, (n - 1) / 4) fT(i * 4, n, 0), fT(n, i * 4, 1);
n += k;
}
break;
}
print();
}
int main() {
int t = 1;
scanf("%d", &t);
while (t--) Solve();
return 0;
}