#include <iostream>
#include <string>
#include <sstream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
ios::sync_with_stdio(false); cin.tie(0);
int T, M, N;
int R[100][100];
cin >> T;
while (T--)
{
int n = 1;
cin >> N >> M;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N - 1 - 2 * i; j++)
{
R[i][i + j] = n++;
}
for (int j = 0; j < N - 1 - 2 * i; j++)
{
R[i + j][N - i - 1] = n++;
}
for (int j = 0; j < N - 1 - 2 * i; j++)
{
R[N - i - 1][N - i - j - 1] = n++;
}
for (int j = 0; j < N - 1 - 2 * i; j++)
{
R[N - i - j - 1][i] = n++;
}
}
if (N % 2)
{
R[N / 2][N / 2] = n;
}
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
if (M == 1)
{
cout << R[i][j] << setw(5);
}
else
{
cout << R[j][i] << setw(5);
}
}
cout << "\n";
}
cout << "\n";
}
}