package javaapplication197;
import java.util.Scanner;
public class JavaApplication197 {
public static void main(String[] args) {
Scanner scn=new Scanner(System.in);
while(scn.hasNext()){
int t=scn.nextInt();
for(int i=0;i<t;i++){
int n=scn.nextInt();
int m=scn.nextInt();
int a[][]=new int[n][n];
int count=1;
for(int ii=1;ii<=n/2;ii++){
for(int j=ii-1;j<=n-ii;j++)
a[ii-1][j]=count++;
count--;
for(int j=ii-1;j<=n-ii;j++)
a[j][n-ii]=count++;
count--;
for(int j=n-ii;j>=ii-1;j--)
a[n-ii][j]=count++;
count--;
for(int j=n-ii;j>ii-1;j--)
a[j][ii-1]=count++;
}
if(n%2==1) a[n/2][n/2]=count--;
for(int j=0;j<n;j++){
for(int k=0;k<n;k++){
if(m==1)System.out.printf("%5d",a[j][k]);
else System.out.printf("%5d",a[k][j]);
}
System.out.println();
}
}
}
}
}