#include<>
const int inf = 99999;
const int N = 101;
int a[N][N],b[N][N],temp[N][N]; //a stores the initial matrix, b is the target state matrix
int n,m;
int need;//Number of transformations required
void ChangeL(int x,int y)//Transform column
{
if(x==y)return;
int i;
for(i=1;i<=n;i++)
{
int tt=temp[i][y];
temp[i][y]=temp[i][x];
temp[i][x]=tt;
}
need++;
}
void ChangeH(int x)//Change lines
{
int i;
for(i=1;i<=m;i++)
{
temp[x][i]^=1;
}
}
bool Same(int x,int y) //Judge whether the column meets the conditions
{
int i;
for(i=1;i<=n;i++)
if(b[i][x]!=temp[i][y])return false;
return true;
}
int main()
{
int tests;
scanf("%d",&tests); //Number of data groups
while(tests--)
{
scanf("%d%d",&n,&m); //n rows, m columns
int i,j;
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
{
scanf("%d",&a[i][j]);
}
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
scanf("%d",&b[i][j]);
int k;
int ans=inf; //ans stores the final answer, the initial value is infinite
for(k=1;k<=m;k++)//Enumeration of each column is the first column
{
for(i=1;i<=n;i++)
for(j=1;j<=m;j++)
temp[i][j]=a[i][j];
need=0;
ChangeL(1,k);
//A one transformation is performed if the row is not satisfied
for(i=1;i<=n;i++)
{
if(temp[i][1]!=b[i][1])//This line does not meet the conditions
{
ChangeH(i);//Change the line
need++;
}
}
bool find;
for(i=1;i<=m;i++)//Check whether each column meets the conditions
{
find=false;
if(Same(i,i))
{
find=true;
continue;
}
for(j=i+1;j<=m;j++)//Look for the same column as i in temp
{
If(Same(i,j))//temp is the same as column i of column b
{
if(Same(j,j))continue;//The j column of temp is the same as the j column of b
ChangeL(i,j);//Exchange the i,j column of temp
find=true;
break;
}
}
if(find==false)//The corresponding column cannot be found
{
break;
}
}
if(find==true&&need<ans)
ans=need;
}
if(ans<inf)
printf("%d\n",ans);
else
printf("-1\n");
}
return 0;
}