1. 程式人生 > >POJ2386 簡單的深搜

POJ2386 簡單的深搜

Lake Counting

Time Limit: 1000MS

Memory Limit: 65536K

Total Submissions: 20765

Accepted: 10463

Description

Due to recent rains, water has pooled in various placesin 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 pondshave formed in his field. A pond is a connected set of squares with water inthem, 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'sfield. Each character is either 'W' or '.'. The characters do not have spacesbetween 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

程式碼:

#include<stdio.h>

int N,M;

char field[110][110];

void dfs(int x, int y)

{

         intdx,dy;

         intnx,ny;

         field[x][y]='.';

         for(dx=-1;dx<=1;dx++)//

迴圈遍歷(xy)周圍的八個點

         {

                   for(dy=-1;dy<=1;dy++)//x方向移動dx,y方向移動dy,移動後為nxny

                   {

                            nx= x + dx;

                            ny= y + dy;

                            if(nx>=0&& ny>=0 && nx<N && ny<M &&field[nx][ny]=='W')

//判斷移動後的點是不是在院子內,以及是否為W

                            {

                                     dfs(nx,ny);

                            }

                   }

         }

         return;

}

int main()

{

         inti,j;

         intnum = 0;

         scanf("%d",&N);

         scanf("%d",&M);

         for(i=0;i<N;i++)//N代表行

         {

                            scanf("%s",&field[i]);

         }

         for(i=0;i<N;i++)

         {

                   for(j=0;j<M;j++)

                   {

                            if(field[i][j]=='W')//從有W的地方開始進行DFS

                            {

                                     dfs(i,j);

                                     num++;

                            }

                   }

         }

         printf("%d\n",num);

         return0 ;

}