Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 25322 | Accepted: 12759 |
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.
Output
* Line 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
思路:
很基础的一道题目,入门级别,有助于理解搜索的本质以及bfs和dfs的区别
这个题可以用“扫雷”的思维来形象的理解,即遇到一个'W',点一下这个点,则与它相邻的一片为‘W’的点都变成‘.’了
而我们只需要从头开始遍历一共有多少个这样的W即可
dfs:
#include <stdio.h>
#define maxn 107 int n,m;
char g[maxn][maxn];
int dir[][] = {{-,-},{-,},{-,},{,-},{,},{,},{,-},{,}}; void dfs(int x,int y){
g[x][y] = '.';//此行代码意义重大,相当于将其置为已访问状态
for(int i = ;i < ;i++) {
int dx = x+dir[i][];
int dy = y+dir[i][];
if(dx>n||dx<||dy<||dy>m)
continue;
if(g[dx][dy] == '.')
continue;
dfs(dx,dy);
}
}
int main()
{
while(scanf("%d%d",&n,&m)!=EOF) {
int ans = ;
for(int i = ;i <= n;i++)
scanf("%s",g[i]+);
int cnt = ;
for(int i = ;i <= n;i++)
for(int j = ;j <= m;j++) {
if(g[i][j] == 'W') {
ans++;
dfs(i,j);//把所有和该点相邻的W都变成.
}
}
printf("%d\n",ans);
}
return ;
}
bfs:
#include <iostream>
#include <cstdio>
#include <queue>
using namespace std; int n,m;
char G[][];
int dir[][] = {{-,-},{-,},{-,},{,-},{,},{,-},{,},{,}};
typedef pair<int,int> node; void bfs(int x,int y)
{
G[x][y] ='.';//比较好的一种处理方法,省去开vis数组
priority_queue<node> q;//q中存储了(x,y)点的所有连通点
q.push(make_pair(x,y));
while(!q.empty())
{
node t = q.top();
q.pop();
int tx = t.first;
int ty = t.second;
for(int i = ;i < ;i++)
{
int dx = tx+dir[i][];
int dy = ty+dir[i][];
if(dx>=&&dx<=n&&dy>=&&dy<=m && G[dx][dy]=='W') {
G[dx][dy] = '.';
q.push(make_pair(dx,dy));
}
}
}
} int main()
{
while(cin>>n>>m)
{
int ans = ;
for(int i = ;i <= n;i++)
scanf("%s",&G[i][]); for(int i = ;i <= n;i++)
for(int j = ;j <= m;j++)
if(G[i][j]=='W') {
bfs(i,j);
ans++;
}
cout<<ans<<endl;
}
return ;
}