1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100
| //#include<bits/stdc++.h> #include <cstdio> #include <cstring> #include <algorithm>
using namespace std; typedef long long ll;
const ll mod = 1e9+7;
int n,m; char mat[200][200]; int vis[200][200];
int dx[4] = {0,0,-1,1}; int dy[4] = {1,-1,0,0};
bool check(int i,int j) { if (i>=1&&i<=n&&j>=1&&j<=m) return true; else return false; }
void dfs(int x,int y,char ch) { vis[x][y] = 1; for (int i = 0 ; i< 4 ; i ++) { if (check(x+dx[i],y+dy[i])&&!vis[x+dx[i]][y+dy[i]]&&mat[x+dx[i]][y+dy[i]]==ch) dfs(x+dx[i],y+dy[i],ch); } return;
}
int main(){ int T;
while (~scanf("%d%d",&n,&m)) { memset(vis,0,sizeof(vis)); for (int i = 1 ; i <= n ; i ++) scanf("%s",mat[i]+1); for (int i = 1 ; i <= n ; i ++) { if (!vis[i][1]&&mat[i][1]=='0') dfs(i,1,'0'); if (!vis[i][m]&&mat[i][m]=='0') dfs(i,m,'0'); } for (int i = 1 ; i <= m ; i ++) { if (!vis[1][i]&&mat[1][i]=='0') dfs(1,i,'0'); if (!vis[n][i]&&mat[n][i]=='0') dfs(n,i,'0'); } int cnt = 0; for (int i = 1 ; i <= n ; i ++) { for (int j = 1 ; j <= m ; j ++) { if (mat[i][j] =='1'&&!vis[i][j]) { cnt++; dfs(i,j,'1'); } } } if (cnt!=1) { printf("-1\n"); continue; } cnt = 0; for (int i = 1 ; i <= n ; i ++) { for (int j = 1 ; j <= m ; j ++) { if (!vis[i][j]&&mat[i][j]=='0') { cnt ++; dfs(i,j,'0'); } } } if (cnt==0) printf("1\n"); else if (cnt==1) printf("0\n"); else printf("-1\n");
} return 0; }
|