首页 > 代码库 > DFS----Lake Counting (poj 2386)
DFS----Lake Counting (poj 2386)
Lake Counting(POJ No.2386)
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.
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.
* 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
1 #include <iostream>
2 using namespace std;
3 int N,M;
4 //int res=0;
5 const int MAX_N=1000;
6 const int MAX_M=1000;
7 char field[MAX_N][MAX_M];
8 void dfs(int x,int y)
9 {
10 field[x][y]=‘.‘;
11 for(int dx=-1;dx<=1;dx++)
12 {
13 for(int dy=-1;dy<=1;dy++)
14 {
15 int nx=dx+x,ny=dy+y;
16 if(nx>=0&&nx<N&&ny>=0&&ny<M&&field[nx][ny]==‘W‘)
17 dfs(nx,ny);
18 }
19 }
20 return;
21 }
22 void solve()
23 {
24 int res=0;
25 for(int i=0;i<N;i++) {
26 for(int j=0;j<M;j++){
27 if(field[i][j]==‘W‘) {
28 dfs(i, j);
29 res++;
30 }
31 }
32 }
33 cout<<res<<endl;
34 }
35 int main() {
36 cin>>N>>M;
37 for(int x=0;x<N;x++)
38 {
39 for(int y=0;y<M;y++)
40 {
41 cin>>field[x][y];
42 }
43 // printf("\n");
44 }
45 solve();
46 //cout<<res<<endl;
47 return 0;
48 }
DFS----Lake Counting (poj 2386)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。