【HDOJ】3329 The Flood

时间:2024-01-21 20:10:09

超简单BFS。

 /* 3329 */
#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <cstdlib>
using namespace std; #define MAXN 105 typedef struct node_t {
int x, y;
node_t() {}
node_t(int xx, int yy) {
x = xx; y = yy;
}
} node_t; int n, m, h, total;
int map[MAXN][MAXN];
bool visit[MAXN][MAXN];
int dir[][] = {
-,,,,,-,,
}; inline bool check(int x, int y) {
return x< || x>=n || y< || y>=m;
} void border_bfs(int x, int y) {
int i, j, k;
int xx, yy;
queue<node_t> Q;
node_t nd; Q.push(node_t(x, y));
visit[x][y] = true; while (!Q.empty()) {
nd = Q.front();
Q.pop();
--total;
for (i=; i<; ++i) {
xx = nd.x + dir[i][];
yy = nd.y + dir[i][];
if (check(xx, yy) || visit[xx][yy] || map[xx][yy]>h)
continue;
visit[xx][yy] = true;
Q.push(node_t(xx, yy));
}
}
} void bfs(int x, int y) {
int xx, yy, s;
int i, j, k;
queue<node_t> Q;
node_t nd; Q.push(node_t(x, y));
visit[x][y] = true; while (!Q.empty()) {
nd = Q.front();
Q.pop();
--total;
for (i=; i<; ++i) {
xx = nd.x + dir[i][];
yy = nd.y + dir[i][];
if (check(xx,yy) || visit[xx][yy])
continue;
visit[xx][yy] = true;
Q.push(node_t(xx, yy));
}
}
} int main() {
int t = ;
int i, j, k, tmp;
bool flag;
int maxh; #ifndef ONLINE_JUDGE
freopen("data.in", "r", stdin);
freopen("data.out", "w", stdout);
#endif while (scanf("%d %d",&n,&m)!=EOF && (n||m)) {
maxh = -;
for (i=; i<n; ++i) {
for (j=; j<m; ++j) {
scanf("%d", &map[i][j]);
if (map[i][j] > maxh)
maxh = map[i][j];
}
}
tmp = n*m;
for (h=; h<maxh; ++h) {
// handle border of map
total = tmp;
memset(visit, false, sizeof(visit));
for (j=; j<m; ++j) {
if (!visit[][j] && map[][j]<=h)
border_bfs(, j);
if (!visit[n-][j] && map[n-][j]<=h)
border_bfs(n-, j);
}
for (i=; i<n; ++i) {
if (!visit[i][] && map[i][]<=h)
border_bfs(i, );
if (!visit[i][m-] && map[i][m-]<=h)
border_bfs(i, m-);
}
// check if there exsits two or more lands
flag = false;
for (i=; i<n; ++i) {
for (j=; j<m; ++j) {
if (!visit[i][j]) {
flag = true;
break;
}
}
if (flag)
break;
}
if (flag) {
bfs(i, j);
if (total > )
break;
}
}
if (h < maxh)
printf("Case %d: Island splits when ocean rises %d feet.\n", ++t, h);
else
printf("Case %d: Island never splits.\n", ++t);
} return ;
}