int t; cin >> t; while (t--) { int n, m; cin >> n >> m; if (n + 1 <= m) { cout << n + 1 << endl; for (int i = 1; i <= n; ++i) { for (int j = i; j <= i + n; ++j) { cout << j % (n + 1) << " "; } for (int j = n + 1; j < m; ++j) { if (j == m - 1) cout << j << "\n"; else cout << j << " "; } } } else { if (m == 1) cout << "0" << endl; else cout << m << endl; for (int i = 1; i <= m - 1; ++i) { for (int j = i; j <= i + m - 1; ++j) { if (j == i + m - 1) cout << j % m << "\n"; else cout << j % m << " "; } } for (int i = 1; i <= n - m + 1; ++i) { for (int j = 1; j <= m; ++j) { if (j == m) cout << 0 << "\n"; else cout << j << " "; } } } }