#include <bits/stdc++.h>
using namespace std;
int main(){
ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0);
int num;
while(cin >> num){
for(int qq = 0; qq<num; qq++){
int n, m, a[110][110] = {0}, cnt = 1, temp;
cin >> n >> m;
if(m == 1)
for(int i = 0; cnt<=n*n; i+=2){
for(int k = i/2; k<n-i/2; k++, cnt++) a[i/2][k] = cnt;
for(int k = i/2+1; k<n-i/2; k++, cnt++) a[k][n-1-i/2] = cnt;
for(int k = n-2-i/2; i/2<=k; k--, cnt++) a[n-1-i/2][k] = cnt;
for(int k = n-2-i/2; i/2<k; k--, cnt++) a[k][i/2] = cnt;
}
else if(m == 2)
for(int i = 0; cnt<=n*n; i+=2){
for(int k = i/2; k<n-i/2; k++, cnt++) a[k][i/2] = cnt;
for(int k = i/2+1; k<n-i/2; k++, cnt++) a[n-1-i/2][k] = cnt;
for(int k = n-2-i/2; i/2<=k; k--, cnt++) a[k][n-1-i/2] = cnt;
for(int k = n-2-i/2; i/2<k; k--, cnt++) a[i/2][k] = cnt;
}
for(int i = 0; i<n; i++)
for(int j = 0; j<n; j++)
cout << setw(5) << a[i][j];
cout << endl;
}
}
return 0;
}