您的位置:首页 > 其它

poj 2386 (Lake Counting)

2016-08-18 17:36 295 查看
Lake Counting

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

题意:类似hdu 1241(油田),求连成片的‘W’有几片。

 题解:DFS  8 个方向。

#include<cstdio>
#include<cstring>
using namespace std;
int n, m, ans;
char map[110][110];
int vis[110][110];//标记是否访问,也可以直接更改map='.'
int dx[8] = {0,0,1,1,1,-1,-1,-1};
int dy[8] = {1,-1,1,-1,0,1,-1,0};

void dfs(int a,int b){
vis[a][b] = 1;
int i;
for (i=0; i<8; i++){
int x= a+ dx[i];
int y= b+ dy[i];
if (map[x][y]== 'W' && x>=0 &&y>=0 &&x<n&& y<m &&!vis[x][y]){
dfs(x,y);
}

}
return ;
}

int main(){
int i, j;
scanf ("%d %d", &n, &m);
ans=0;
memset (vis,0,sizeof(vis));
for (i= 0; i< n; i++){
getchar();
scanf ("%s", map[i]);
}
for (i=0; i<n; i++){//需要重新开一个循环,不能合并到输入那里。
for (j=0; j<m; j++){
if (map[i][j]== 'W'&&!vis[i][j]){
dfs(i,j);
ans++;
}

}
}
printf ("%d\n",ans);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: