#include<cstdio>#include<cstring>#include<algorithm>usingnamespace std;#define N 1010#define md 1000000007int a[N][N], A[N], L[N], R[N], st[N][2];intread(){int s =0;char x =getchar();while(x <'0'|| x >'9') x =getchar();while(x >='0'&& x <='9') s = s *10+ x -48, x =getchar();return s;}voidturn(int x){int s = st[x][0]+ st[x][1];for(int i = st[x][0]; i < s - i; i++)swap(A[i], A[s - i]);}intmain(){int tn =read();while(tn--){int n =read(), m =read(), i, j;memset(A,0,sizeof(A));for(i =1; i <= n; i++){for(j =1; j <= m; j++)scanf("%d",&a[i][j]);
L[i]=1, R[i]= m;}int tot =1, s =1;
st[1][0]=1, st[1][1]= m;for(j = m; j && s; j--){for(i =1; i <= n; i++){if(!A[L[i]]&&!A[R[i]]) s = s *((L[i]!= R[i])+1)% md, A[L[i]++]= a[i][j];elseif(A[L[i]]== a[i][j]) L[i]++;elseif(A[R[i]]== a[i][j]) R[i]--;elseif(A[L[i]]!= a[i][j]&& A[R[i]]==0) A[R[i]--]= a[i][j];elseif(A[R[i]]!= a[i][j]&& A[L[i]]==0) A[L[i]++]= a[i][j];else{
s =0;break;}}int ok =1;for(i =2; i <= n && ok; i++)if((L[i]!= L[i -1]|| R[i]!= R[i -1])) ok =0;if(ok) st[++tot][0]= L[1], st[tot][1]= R[1];}printf("%d\n", s);if(s){for(j = tot; j; j--){if(j < tot && st[j][1]== st[j +1][1]){if(A[st[j][0]]> A[st[j +1][0]])turn(j +1),turn(j);}else{if(st[j][0]< st[j][1]&& A[st[j][0]]> A[st[j][1]]){if(j < tot)turn(j +1);turn(j);}}}for(i =1; i <= m; i++)printf("%d ", A[i]);puts("");}}return0;}