#include #include #define rep(i,n) for(int i=0;i dist(0, 1); int solve(){ int n, m; cin >> n >> m; bool FLIP = false; auto v2 = [&](int x){ int res = 0; while(x % 2 == 0){ res++; x /= 2; } return res; }; if(v2(n) + v2(m) <= 2){ cout << "-1\n"; return 0; } if(v2(n) > v2(m)){ swap(n, m); FLIP = true; } int cnt = 0; vector> a(n, vector(m)); vector> B = {{1, 1, 1, 2}, {1, 2, 2, 2}}; auto set_B = [&](int si, int sj){ rep(di, 2) rep(dj, 4){ a[si + di][sj + dj] = cnt + B[di][dj]; } cnt += 2; }; vector> C = {{1, 1, 3, 3, 3, 4, 6, 6}, {1, 2, 3, 4, 4, 4, 5, 6}, {1, 2, 2, 2, 5, 5, 5, 6}}; auto set_C = [&](int si, int sj){ rep(di, 3) rep(dj, 8){ a[si + di][sj + dj] = cnt + C[di][dj]; } cnt += 6; }; // case (II) if(v2(n) >= 1 and v2(m) >= 2){ int k = n * m / 4; rep(i, n / 2) rep(j, m / 4){ set_B(i * 2, j * 4); } cout << k << "\n"; if(FLIP){ vector> a_old(m, vector(n)); swap(a, a_old); rep(i, n) rep(j, m) a[j][i] = a_old[i][j]; swap(n, m); } int r = dist(mt); if(r == 1){ vector> a_old = a; rep(i, n) rep(j, m) a[i][j] = a_old[(n - 1) - i][(m - 1) - j]; } rep(i, n){ rep(j, m) cout << a[i][j] << (j == m - 1 ? "\n" : " "); } return 0; } // case (III) if(v2(n) == 0 and v2(m) >= 3){ if(n == 1){ cout << "-1\n"; return 0; } int k = n * m / 4; int n2 = n / 2 - 1; int m2 = m / 4; rep(i, n / 2 - 1) rep(j, m / 4){ set_B(i * 2, j * 4); } rep(j, m / 8){ set_C(n - 3, j * 8); } cout << k << "\n"; if(FLIP){ vector> a_old(m, vector(n)); swap(a, a_old); rep(i, n) rep(j, m) a[j][i] = a_old[i][j]; swap(n, m); } int r = dist(mt); if(r == 1){ vector> a_old = a; rep(i, n) rep(j, m) a[i][j] = a_old[(n - 1) - i][(m - 1) - j]; } rep(i, n){ rep(j, m) cout << a[i][j] << (j == m - 1 ? "\n" : " "); } return 0; } assert(false); return 0; } int main(){ int t; cin >> t; for(int i = 0; i < t; i++) solve(); }