POJ 2386 Lake Counting(dfs or bfs)

来源:互联网 发布:java计算器gui 编辑:程序博客网 时间:2024/06/09 23:55
Lake Counting

Time Limit: 1000MS


Memory Limit: 65536K

Total Submissions: 24999


Accepted: 12619

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 12W........WW..WWW.....WWW....WW...WW..........WW..........W....W......W...W.W.....WW.W.W.W.....W..W.W......W...W.......W.

Sample Output

3


题意:图给出的是一片农场,'W'表示水, '.' 表示土地。问这片农场有多少块池塘。


dfs解法:从任意的W开始,不停地把邻接的部分用‘.’代替。1次dfs后与初始的W连接的所有W就都被替换成了‘.’ ,

直到图中不再存在W为止,总共进行的dfs次数就是答案。


代码如下:


#include<cstdio>int n,m;char map[110][110];int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};void dfs(int x,int y){int i,nowx,nowy;map[x][y]='.';//将W替换成‘.’ for(i=0;i<8;++i)//遍历它的旁边8个方向 {nowx=x+dir[i][0];nowy=y+dir[i][1];if(nowx>=0&&nowx<n&&nowy>=0&&nowy<m&&map[nowx][nowy]=='W')dfs(nowx,nowy);}}int main(){int i,j,cnt;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<n;++i)scanf("%s",map[i]);cnt=0;for(i=0;i<n;++i){for(j=0;j<m;++j){if(map[i][j]=='W'){dfs(i,j);cnt++;}}}printf("%d\n",cnt);}return 0;} 



bfs解法,解题思想与dfs一致,时间和内存也差不多

代码如下:


#include<cstdio>#include<queue>using namespace std;#define maxn 110char map[maxn][maxn];int n,m;int dir[8][2]={{-1,-1},{-1,0},{-1,1},{0,-1},{0,1},{1,-1},{1,0},{1,1}};struct node{int x,y;}a,temp;void bfs(int x,int y){int i;queue<node>q;a.x=x;a.y=y;q.push(a);map[x][y]='.';while(!q.empty()){a=q.front();q.pop();for(i=0;i<8;++i){temp.x=a.x+dir[i][0];temp.y=a.y+dir[i][1];if(temp.x>=0&&temp.x<n&&temp.y>=0&&temp.y<m&&map[temp.x][temp.y]=='W'){q.push(temp);map[temp.x][temp.y]='.';}} }}int main(){int i,j,cnt;while(scanf("%d%d",&n,&m)!=EOF){for(i=0;i<n;++i)scanf("%s",map[i]);cnt=0;for(i=0;i<n;++i){for(j=0;j<m;++j){if(map[i][j]=='W'){bfs(i,j);cnt++;}}}printf("%d\n",cnt);}return 0;}






0 0