1. 程式人生 > >題解報告:poj 2386 Lake Counting

題解報告:poj 2386 Lake Counting

oid recent not std sep number tchar 次數 tails

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

Hint

OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side. 解題思路:從任意的‘W‘開始,不停地把鄰接的部分用‘.‘代替。一次DFS後與初始的這個‘W‘連接的所有‘W‘就被替換成了‘.‘,因此直到圖中不再存在‘W‘為止,總共進行的DFS的次數就是最終答案。 AC代碼:
 1 #include<iostream>
 2 #include<cstdio>
 3 using
namespace std; 4 const int maxn=105; 5 int n,m,res;char mp[maxn][maxn]; 6 void dfs(int x,int y){ 7 mp[x][y]=.; 8 for(int dx=-1;dx<=1;++dx){ 9 for(int dy=-1;dy<=1;++dy){ 10 int nx=x+dx,ny=y+dy; 11 if(0<=nx && nx<n && 0<=ny && ny<m && mp[nx][ny]==W)dfs(nx,ny);//往8個方向尋找‘W‘的點 12 } 13 } 14 return; 15 } 16 int main(){ 17 while(~scanf("%d%d",&n,&m)){ 18 for(int i=0;i<n;++i){ 19 getchar(); 20 for(int j=0;j<m;++j) 21 scanf("%c",&mp[i][j]); 22 } 23 res=0; 24 for(int i=0;i<n;++i) 25 for(int j=0;j<m;++j) 26 if(mp[i][j]==W){dfs(i,j);res++;} 27 printf("%d\n",res); 28 } 29 return 0; 30 }

題解報告:poj 2386 Lake Counting