#include <bits/stdc++.h>
using namespace std;
void run_case()
{
int n,m;
cin>> n >> m;
bool valid = true;
bool hadone = false;
vector <string> matrix;
vector <vector <int>> oilfield;
for(int i = 0;i<n;i++){
string o;
cin>>o;
vector <int > v;
matrix.push_back(o);
for(int j = 0;j<m;j++){
if(o[j] == '1'){
hadone = true;
v.push_back(j);
if(v.size() > 1){
if(v[v.size()-1] - v[v.size()-2] > 1) valid = false;
}
}
}
v.push_back(i);
oilfield.push_back(v);
}
/*
cout<<endl;
for(int i = 0;i<oilfield.size();i++){
for(int j = 0;j<oilfield[i].size();j++){
cout<<oilfield[i][j];
}
cout<<endl;
}
*/
for(int i = 1;i<oilfield.size();i++){
if(oilfield[i][oilfield[i].size()-1] - oilfield[i-1][oilfield[i-1].size()-1] > 1){
valid = false;
}
if(oilfield[i].size() - oilfield[i-1].size() != 0 && (oilfield[i].size() != 1 && oilfield[i-1].size() != 1)){
valid = false;
break;
}
if(oilfield[i].size() > 1 && oilfield[i-1].size() > 1){
for(int j = 0; j < oilfield[i].size()-2;j++){
if(oilfield[i][j] != oilfield[i-1][j]) valid = false;
}
}
if(valid == false) break;
}
if(valid == false || hadone == false) cout<<0<<endl;
else cout<<1<<endl;
}
int main()
{
int t;
cin>>t;
while(t-->0){
run_case();
}
return 0;
}