度度熊的01世界
Accepts: 967
Submissions: 3064
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 32768/32768 K (Java/Others)
思路:图像1,0都有一句描述:存在1字符且1字符只能是由一个联通块组成,所以,先统计1字符联通块数,不等于1,输出-1
再统计被1完全包围的0字符联通块数,一个输出0,0个输出1,否则输出-1
#include <cstdio>
#include <cstring>
using namespace std;
const int N = 111;
char rec[N][N];
bool vis[N][N];
int dir[4][2] = {1, 0, 0, 1, -1, 0, 0, -1};
int n, m;
void dfs(int x, int y)
{
vis[x][y] = 1;
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0], ty = y + dir[i][1];
if (tx < 0 || ty < 0 || tx >= n || ty >= m || vis[tx][ty])continue;
if (rec[tx][ty] != '1')continue;
dfs(tx, ty);
}
}
void dfs0(int x, int y, bool &judge)
{
vis[x][y] = 1;
if (x == 0 || x == n - 1 || y == 0 || y == m - 1)
{
judge = false;
}
for (int i = 0; i < 4; i++)
{
int tx = x + dir[i][0], ty = y + dir[i][1];
if (tx < 0 || ty < 0 || tx >= n || ty >= m || vis[tx][ty])continue;
if (rec[tx][ty] != '0')continue;
dfs0(tx, ty, judge);
}
}
int main()
{
while (~scanf("%d%d", &n, &m))
{
for (int i = 0; i < n; i++)
scanf("%s", rec[i]);
memset(vis, 0, sizeof(vis));
int cnt = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) if (rec[i][j] == '1')
if (!vis[i][j])
{
dfs(i, j);
cnt++;
}
if (cnt != 1)
{
printf("-1\n");
continue;
}
int zero = 0;
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++) if (rec[i][j] == '0')
if (!vis[i][j])
{
bool judge = true;
dfs0(i, j, judge);
if (judge)
zero++;
}
if (zero == 1)
{
printf("0\n");
continue;
}
if (zero == 0)
puts("1");
else
puts("-1");
}
return 0;
}