2017百度之星初赛(A) 度度熊的01世界(BFS/DFS)

来源:互联网 发布:日本网络电视jitakutv 编辑:程序博客网 时间:2024/06/06 01:47

又是一次死于读题的操作,游戏体验十分差。

队友都是用dfs干掉了,我写的bfs半天过不了,然后拿他们程序对拍数据才发现这里没理解到,那里没理解到。

bfs的做法为:

1.首先把边界上的0全部去掉。

2.判断是否只有一个字符为1的联通块

3. 如果没有或者多于一个,答案为-1

如果只有一个

4.判断还有多少个字符为0的联通块

5. 如果没有,则答案为1

如果有一个,答案为0

否则答案为-1

代码如下:

#include<iostream>#include<cstdio>#include<vector>#include<queue>#include<utility>#include<stack>#include<algorithm>#include<cstring>#include<string>#include<cmath>using namespace std;const int maxn = 105;typedef pair<int, int> pii;int dir[][2] = {0,1,0,-1,1,0,-1,0};char G[maxn][maxn];bool vst[maxn][maxn];int n, m;bool Check(int x, int y, char ch) {if(x >= 0 && x <= n + 1 && y >= 0 && y <= m + 1 && !vst[x][y] && G[x][y] == ch)return 1;return 0;}void bfs(int x, int y, char ch) {queue <pii> q;q.push(pii(x, y));pii now, next;vst[x][y] = 1;while(!q.empty()) {now = q.front();q.pop();for(int i = 0; i < 4; i++) {next.first = now.first + dir[i][0];next.second = now.second + dir[i][1];if(Check(next.first, next.second, ch)) {q.push(next);vst[next.first][next.second] = 1;}}}}int main() {#ifndef ONLINE_JUDGEfreopen("in.txt", "r", stdin);//    freopen("out.txt", "w", stdout);#endifbool flag;int cnt;while(scanf("%d%d", &n, &m) != EOF) {for(int i = 0; i < maxn; i++) {for(int j = 0; j < maxn; j++) G[i][j] = '0';}memset(vst, 0, sizeof(vst));int ans = -1;for(int i = 1; i <= n; i++) {scanf("%s", G[i] + 1);G[i][m + 1] = '0';}bfs(0, 0, '0');cnt = 0; for(int i = 1; i <= n; i++) {for(int j = 1; j <= m; j++) {if(!vst[i][j] && G[i][j] == '1') {bfs(i, j, '1');cnt++;}}}if(cnt == 1) {cnt = 0;for(int i = 1; i <= n; i++) {for(int j = 1; j <= m; j++) {if(!vst[i][j] && G[i][j] == '0') {bfs(i, j, '0');cnt++;}}}if(cnt == 0)ans = 1;else if(cnt == 1)ans = 0;elseans = -1;}elseans = -1;cout << ans << '\n';}return 0;}


阅读全文
0 0