今天对搜索的小练习,这个是很经典的DFS题目——“八连通”。
传送门:http://poj.org/problem?id=2386
Lake Counting
Time Limit: 1000MS Memory Limit: 65536K
Total Submissions: 38373 Accepted: 19051
Description
Due to recent rains, water has pooled in various places in Farmer John’s field, which is represented by a rectangle of N x M (1 <= N <= 100; 1 <= M <= 100) squares. Each square contains either water (‘W’) or dry land (‘.’). Farmer John would like to figure out how many ponds have formed in his field. A pond is a connected set of squares with water in them, where a square is considered adjacent to all eight of its neighbors.
Given a diagram of Farmer John’s field, determine how many ponds he has.
Input
Line 1: Two space-separated integers: N and M
Lines 2..N+1: M characters per line representing one row of Farmer John’s field. Each character is either ‘W’ or ‘.’. The characters do not have spaces between them.
OutputLine 1: The number of ponds in Farmer John’s field.
Sample Input
10 12
W........WW.
.WWW.....WWW
....WW...WW.
.........WW.
.........W..
..W......W..
.W.W.....WW.
W.W.W.....W.
.W.W......W.
..W.......W.
Sample Output
3
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source
USACO 2004 November
题意呢很好理解,就是让你找出连在一块的pond有多少,这里的连通不限于是上下左右相邻,而是周围八个点都可以,有点像扫雷的意思啊……然后你就输出这样的大块有多少就行了。
具体做法可以由DFS来实现,值得注意的是,这里并没有要求返回什么东西,所以只要发现一块水池后就将其变为 ‘.’;不会影响后面的进程。
我做这题时没看W是大写还是小写,WA了一次。。。要看清题目啊!!!
还有DFS的实现,因为对递归的写法不怎么喜欢。。。我比较喜欢用显式的stack来写出来。
AC代码如下:
#include <cstdio>
#include <cstring>
#include <stack>
#include <algorithm>
using namespace std;
const int maxn = 102;
const int mas = 8;
char field[maxn][maxn];
int vis[maxn][maxn];
int n, m;
struct Node
{
int x, y;
int step;
};
int dx[mas] = {0, 0, 1, 1, 1, -1, -1, -1};
int dy[mas] = {1, -1, 1, -1, 0, 0, 1, -1};
stack<Node> lake;
void DFS(int x, int y)
{
while(!lake.empty()) lake.pop();
memset(vis, 0, sizeof(vis));
Node beg;
beg.x = x, beg.y = y, beg.step = 0;
lake.push(beg);
vis[beg.x][beg.y] = 1;
field[beg.x][beg.y] = '.';
while(!lake.empty())
{
Node cur = lake.top();
lake.pop();
for(int i = 0; i < 8; i++)
{
Node next;
next.x = cur.x + dx[i];
next.y = cur.y + dy[i];
if(next.x < 0 || next.x >= n || next.y < 0 || next.y >= m) continue;
if(vis[next.x][next.y] || field[next.x][next.y] == '.') continue;
next.step = cur.step + 1;
vis[next.x][next.y] = 1;
lake.push(next);
field[next.x][next.y] = '.';
}
}
return;
}
int main()
{
while(scanf("%d %d", &n, &m) != EOF && (n || m))
{
for(int i = 0; i < n; i++)
scanf("%s", field[i]);
int ans = 0;
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
if(field[i][j] == 'W')
{
DFS(i, j);
ans++;
}
}
}
printf("%d\n", ans);
}
return 0;
}