• 2015 HUAS Summer Training#2 G


    题目:

    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.
     

    题目大意: 找出池塘的个数,连在一起的W算一个池塘

    解题思路:用种子填补法,利用双重循环和递归的方式(以某个点为中心向它的8个方向扫描)

    如:

     1 void dfs(int r,int c,int id)
     2 {
     3     if(r<0||r>=m||c<0||c>=n)        //越界约束
     4         return;
     5     if(b[r][c]>0||a[r][c]!='W')       //防重复查找和排除不是目标的点
     6         return;
     7     b[r][c]=id;                       
     8     for(int dr=-1;dr<=1;dr++)               
     9         for(int dc=-1;dc<=1;dc++)
    10             if(dr!=0||dc!=0)
    11                 dfs(r+dr,c+dc,id);
    12 }

    代码:

     1 #include<iostream>
     2 #include<cstdio>
     3 #include<cstring>
     4 using namespace std;
     5 const int maxn=100+5;
     6 char a[maxn][maxn];
     7 int m,n,b[maxn][maxn];
     8 void dfs(int r,int c,int id)
     9 {
    10     if(r<0||r>=m||c<0||c>=n)
    11         return;
    12     if(b[r][c]>0||a[r][c]!='W')
    13         return;
    14     b[r][c]=id;
    15     for(int dr=-1;dr<=1;dr++)
    16         for(int dc=-1;dc<=1;dc++)
    17             if(dr!=0||dc!=0)
    18                 dfs(r+dr,c+dc,id);
    19 }
    20 int main()
    21 {
    22     int i,j;
    23     while(scanf("%d %d",&m,&n)==2 &&m &&n)
    24     {
    25         for( i=0;i<m;i++)
    26             scanf("%s",a[i]);
    27         memset(b,0,sizeof(b));
    28         int cnt=0;
    29         for( i=0;i<m;i++)
    30             for( j=0;j<n;j++)
    31                 if(b[i][j]==0&&a[i][j]=='W')
    32                     dfs(i,j,++cnt);
    33                 printf("%d
    ",cnt);
    34     }
    35     return 0;
    36 }
  • 相关阅读:
    17111 Football team
    Train Problem I (HDU 100题纪念)
    迷宫问题
    图形点扫描
    看病要排队(stl)
    水果
    Prime Ring Problem
    N皇后问题
    2^x mod n = 1
    Queuing
  • 原文地址:https://www.cnblogs.com/huaxiangdehenji/p/4674693.html
Copyright © 2020-2023  润新知