zoukankan      html  css  js  c++  java
  • DFS----Lake Counting (poj 2386)

    Lake Counting(POJ No.2386)

    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
     1 #include <iostream>
     2 using namespace std;
     3 int N,M;
     4 //int res=0;
     5 const int MAX_N=1000;
     6 const int MAX_M=1000;
     7 char field[MAX_N][MAX_M];
     8 void dfs(int x,int y)
     9 {
    10     field[x][y]='.';
    11     for(int dx=-1;dx<=1;dx++)
    12     {
    13         for(int dy=-1;dy<=1;dy++)
    14         {
    15             int nx=dx+x,ny=dy+y;
    16             if(nx>=0&&nx<N&&ny>=0&&ny<M&&field[nx][ny]=='W')
    17                 dfs(nx,ny);
    18         }
    19     }
    20     return;
    21 }
    22 void solve()
    23 {
    24     int res=0;
    25     for(int i=0;i<N;i++) {
    26         for(int j=0;j<M;j++){
    27             if(field[i][j]=='W') {
    28                 dfs(i, j);
    29                 res++;
    30             }
    31         }
    32     }
    33     cout<<res<<endl;
    34 }
    35 int main() {
    36     cin>>N>>M;
    37     for(int x=0;x<N;x++)
    38     {
    39         for(int y=0;y<M;y++)
    40         {
    41             cin>>field[x][y];
    42         }
    43        // printf("
    ");
    44     }
    45     solve();
    46     //cout<<res<<endl;
    47     return 0;
    48 }
  • 相关阅读:
    <p>1、查询端口号占用,根据端口查看进程信息</p>
    CentOS查询端口占用和清除端口占用的程序
    Spring Boot Maven 打包可执行Jar文件!
    linux下运行jar
    maven 工程mybatis自动生成实体类
    java反射教程
    SQL Server 文件和文件组
    Angular CLI 使用教程指南参考
    mac osx 下 浏览器 开启 java
    es 查询分词字段为空的数据
  • 原文地址:https://www.cnblogs.com/guohaoyu110/p/6770724.html
Copyright © 2011-2022 走看看