DFS----Lake Counting (poj 2386)
Posted 女王公园的八神
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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)的主要内容,如果未能解决你的问题,请参考以下文章