The number of ponds——DFS

来源:互联网 发布:js new cookie 编辑:程序博客网 时间:2024/05/16 15:16

地址:http://acm.hust.edu.cn/vjudge/contest/view.action?cid=62709#problem/B

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 12W........WW..WWW.....WWW....WW...WW..........WW..........W....W......W...W.W.....WW.W.W.W.....W..W.W......W...W.......W.

Sample Output

3

 

题意分析:

一个‘W’是一个pond,如果有其它的‘W’和这个相连(在这个的前、后、左、右、斜方向)那么认为他们一起算是一个Pond,统计一块地中一共有多少个pond

#include<stdio.h>
#include<string.h>
int dir[8][2]={{0,1},{0,-1},{1,0},{-1,0},{1,1},{1,-1},{-1,-1},{-1,1}};
int row,column;
char a[110][110];
int visit[110][110];
void dfs(int x,int y)//写xy可以,但是下边不能用x=x+dir[i][0],y=y+dir[i][1],,因为由题x。y代表坐标在进行递归的时候坐标改变,但是递归完成后坐标还应该是从x,y开始变。例如:初始x,y为(1,1)在递归完成后再从(1,2)开始查找。如果按题中写递归完成后x,y不是这样的。。。

可以将定义改一下

void  dfs(int t,int j
{
 if(visit[x][y]!=0 || a[x][y]=='.')
  return ;
 visit[x][y]=1;
 for(int i=0;i<8;i++)
 {
  x=x+dir[i][0];
  y=y+dir[i][1];
//需要判断x,y是否越界,如果有越界是无法完成执行的、、、可以改成 int  x=t+dir【i】【0】;int  y=j+dir【i】【1】;dfs(x,y);从初始  t,j进行变化得到的坐标

if ( x>=1 && x<=row && y>=1 && y<=column)
     dfs(x,y);
 }
}
int main()
{
 while(scanf("%d%d",&row,&column)!=EOF)
 {
  memset(visit,0,sizeof(visit));
  int i,j,sum=0;
  for(i=1;i<=row;i++)
  {
    scanf("%s",a[i]+1);
  }
  int x,y;
  for(x=1;x<=row;x++)
  {
   for(y=1;y<=column;y++)
   {
    if(a[x][y]=='W' && visit[x][y]==0)
    {
     dfs(x,y);
     sum++;
    }
   }
  }
  printf("%d\n",sum);
 }
 return 0;
}

0 0