#include
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
#define LL long long
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ms(x,y) memset(x,y,sizeof x)
#define ri(x) scanf("%d",&x)
#define rl(x) scanf("%lld",&x)
#define rs(x) scanf("%s",x+1)
#define oi(x) printf("%d",x)
#define ol(x) printf("%lld",x)
#define oc putchar(' ')
#define os(x) printf(x)
#define all(x) x.begin(),x.end()
#define Open() freopen("F:\\rush.txt","r",stdin)
#define Close() ios::sync_with_stdio(0)
typedef pair pii;
typedef pair pll;
const int dx[9] = {0,1,-1,0,0,-1,-1,1,1};
const int dy[9] = {0,0,0,-1,1,-1,1,-1,1};
const double pi = acos(-1.0);
const int N = 110;
int n,m;
char s[N][N];
bool vis[N][N];
queue dl;
int main(){
//Open();
//Close();
while (~ri(n)){
ms(vis,0);
ri(m);
rep1(i,1,n) rs(s[i]);
dl.push(mp(0,0));
while (!dl.empty()){
int x = dl.front().first,y = dl.front().second;
dl.pop();
rep1(i,1,4){
int tx = x + dx[i],ty = y + dy[i];
if (tx >= 0 && tx <= n+1 && ty >= 0 && ty <= m+1){
if (!vis[tx][ty]){
if (tx >=1 && tx <= n && ty >= 1 && ty <= m)
if (s[tx][ty]=='1') continue;
vis[tx][ty] = 1;
dl.push(mp(tx,ty));
}
}
}
}
//return 0;
int nei1 = 0;
rep1(i,1,n)
rep1(j,1,m)
if (s[i][j]=='1' && !vis[i][j]){
nei1++;
vis[i][j] = 1;
dl.push(mp(i,j));
while (!dl.empty()){
int x = dl.front().first,y = dl.front().second;
dl.pop();
rep1(i,1,4){
int tx = x + dx[i],ty = y + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m){
if (s[tx][ty]=='1' && !vis[tx][ty]){
vis[tx][ty] = 1;
dl.push(mp(tx,ty));
}
}
}
}
}
if (nei1==0 || nei1 > 1){
puts("-1");
continue;
}
int nei0 = 0;
rep1(i,1,n)
rep1(j,1,m)
if (s[i][j]=='0' && !vis[i][j]){
nei0++;
vis[i][j] = 1;
dl.push(mp(i,j));
while (!dl.empty()){
int x = dl.front().first,y = dl.front().second;
dl.pop();
rep1(i,1,4){
int tx = x + dx[i],ty = y + dy[i];
if (tx >= 1 && tx <= n && ty >= 1 && ty <= m){
if (s[tx][ty]=='0' && !vis[tx][ty]){
vis[tx][ty] = 1;
dl.push(mp(tx,ty));
}
}
}
}
}
if (nei1 == 1 && nei0 == 1){
puts("0");
continue;
}
if (nei1 == 1 && nei0 == 0){
puts("1");
continue;
}
puts("-1");
}
return 0;
}