题目:这里写链接内容
思路:在n*m图像周围围一圈’0’,然后找0和1的联通块数,1联通块数肯定为1才行;0联通块数如果满足“图像0的定义”,那么必须只有两个联通块,满足“图像1的定义”,必须只有一个联通块。
代码:
#include<bits/stdc++.h>
using namespace std;
const int N = 105;
char s[N][N];
int vis[N][N];
int dx[4] = {1,-1,0,0};
int dy[4] = {0,0,1,-1};
int n,m;
void dfs(int x,int y)
{
vis[x][y] = 1;
for(int i = 0;i < 4;i++)
{
int tx = x + dx[i];
int ty = y + dy[i];
if(!vis[tx][ty] && (tx >= 0 && tx <= n+1 && ty >= 0 && ty <= m+1))
{
if(s[x][y] == s[tx][ty])
dfs(tx,ty);
}
}
}
int main()
{
while(~scanf("%d%d",&n,&m))
{
for(int i = 1;i <= n;i++)
scanf("%s",s[i]+1);
for(int i = 0;i <= n+1;i++)
s[i][0] = s[i][m+1] = '0';
for(int i = 0;i <= m+1;i++)
s[0][i] = s[n+1][i] = '0';
memset(vis,0,sizeof(vis));
int sum1 = 0,sum0 = 0;
for(int i = 0;i <= n+1;i++)
for(int j = 0;j <= m+1;j++)
{
if(vis[i][j])
continue;
if(s[i][j] == '1')
sum1++;
if(s[i][j] == '0')
sum0++;
dfs(i,j);
}
if(sum1 != 1)
{
printf("-1\n");
continue;
}
if(sum0 == 1)
printf("1\n");
else if(sum0 == 2)
printf("0\n");
else
printf("-1\n");
}
return 0;
}