#include <bits/stdc++.h>
using namespace std;
#define int long long
int n, m;
bool valid(int i, int j){
return i>=0 and i<n and j>=0 and j<n;
}
signed main(){
ios::sync_with_stdio(false);
cin.tie(0); cout.tie(0);
int t; cin>>t;
while(t--){
cin>>n>>m;
vector<vector<int>> matrix(n, vector<int>(n, 0));
int i(0), j(0), cnt(1);
matrix[i][j]=cnt;
while(cnt<n*n){
while(valid(i, j+1) and matrix[i][j+1]==0) matrix[i][++j]=++cnt;
while(valid(i+1, j) and matrix[i+1][j]==0) matrix[++i][j]=++cnt;
while(valid(i, j-1) and matrix[i][j-1]==0) matrix[i][--j]=++cnt;
while(valid(i-1, j) and matrix[i-1][j]==0) matrix[--i][j]=++cnt;
}
if(m==2)
for(int i=0; i<n-1; i++)
for(int j=i+1; j<n; j++)
swap(matrix[i][j], matrix[j][i]);
for(auto arr : matrix){
for(auto val : arr) cout<<val<<setw(5);
cout<<'\n';
}
cout<<'\n';
}
return 0;
}