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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
题目意思:查找所有由w组成的区域,八面搜索,只要周围有w就能连接在一起组成一个区域。
解题思路:这是一道很基本的深搜例题,当成模板直接来使用吧。
上代码:
1 #include<stdio.h> 2 #include<string.h> 3 #include<algorithm> 4 #include<iostream> 5 using namespace std; 6 char map[110][110]; 7 int vis[110][110];///标记数组 8 int dir[8][2]={{1,0},{-1,0},{0,1},{0,-1},{1,1},{-1,-1},{1,-1},{-1,1}}; 9 int n,m; 10 void DFS(int x,int y) 11 { 12 int a,b,i; 13 vis[x][y]=1; 14 for(i=0;i<8;i++) 15 { 16 a=x+dir[i][0]; 17 b=y+dir[i][1]; 18 if(a>=0&&a<n&&b>=0&&b<m&&vis[a][b]==0&&map[a][b]=='W') 19 { 20 DFS(a,b); 21 } 22 } 23 return ; 24 } 25 int main() 26 { 27 int count,i,j; 28 memset(map,0,sizeof(map)); 29 memset(vis,0,sizeof(vis)); 30 scanf("%d%d",&n,&m); 31 getchar(); 32 count=0; 33 for(i=0;i<n;i++) 34 { 35 scanf("%s",map[i]); 36 } 37 for(i=0;i<n;i++) 38 { 39 for(j=0;j<m;j++) 40 { 41 if(vis[i][j]==0&&map[i][j]=='W') 42 { 43 count++; 44 DFS(i,j); 45 } 46 } 47 } 48 printf("%d\n",count); 49 return 0; 50 }