#include <bits/stdc++.h>
using namespace std;
int main(){
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
int t;
cin >> t;
while(t--){
int n, m;
cin >> n >> m;
int x[n][n] = {0}, s = 3 - 2*m;
for(int i = n*2, a = 0, b = 0, tmp = 1; i > 0; --i){
for(int j = i/2; j > 0; --j){
x[a][b] = tmp;
++tmp;
if(j != 1) a += (m - 1)%2, b += (-m + 2)%2;
/*if(m == 1) ++b;
else if(m == 2) ++a;
else if(m == 3) --b;
else --a;*/
}
m = (m + s + 4)%4;
a += (m - 1)%2, b += (-m + 2)%2;
}
for(int i = 0; i < n; ++i){
for(int j = 0; j < n; ++j) cout << setw(5) << x[i][j];
cout << '\n';
}
cout << '\n';
}
return 0;
}