#include <bits/stdc++.h>
using namespace std;

using ll = long long;

void Anas() {
    int n,m; cin >> n >> m;
    int mn = min(n,m);
    mn = 1<<mn;
    // cout << mn;
    int mx = max(n,m);
    mn = min(mn,mx);
    cout << mn <<"\n";
    if(m >= n){
    	int cnt = 1;
    	for(int i = 1; i <= n; i++){
    		for(int j = 1; j <= cnt; j++){
    			cout << "1" <<" ";
    		}
    		int x = 2;
    		for(int j = 1; j <= (m - cnt); j++){
    			cout << x <<" ";
    			x++;
    		}
    		cnt++;
    		cout <<"\n";
    	}
    	return;
    }
 	for(int i = 1; i <= n; i++){
 		int x = i;
 		for(int j = 1; j <= m; j++){
 			if(x == 1){
 				cout << 1 <<" ";
 				continue;
 			}
 			cout << x <<" ";
 			x--;
 		}
 		cout <<"\n";
 	}
}

int32_t main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    
    int test = 1;
    cin >> test;

    while (test--) {
       Anas();
    }
    
    return 0;
}
