博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
POJ2386:Lake Counting(DFS)
阅读量:4947 次
发布时间:2019-06-11

本文共 1910 字,大约阅读时间需要 6 分钟。

Lake Counting
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14776   Accepted: 7496

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

Hint

OUTPUT DETAILS:  
There are three ponds: one in the upper left, one in the lower left,and one along the right side.

Source

 

MYCode:

#include<iostream>

#include<cstring>
#include<cstdio>
#define MAX 110
char map[MAX][MAX];
bool vis[MAX][MAX];
int dirt[8][2]={
{1,0},{-1,0},{0,1},{0,-1},{1,1},{1,-1},{-1,1},{-1,-1}};
using namespace std;
void dfs(int x,int y)
{
    vis[x][y]=1;
    int i;
    int tx,ty;
    for(i=0;i<8;i++)
    {
        tx=x+dirt[i][0];
        ty=y+dirt[i][1];
        if(!vis[tx][ty] && map[tx][ty]=='W')
        {
            dfs(tx,ty);
        }
    }
}

int main()

{
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF)
    {
        int i,j;
        memset(vis,0,sizeof(vis));
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                cin>>map[i][j];
            }
        }
        int ans=0;
        for(i=1;i<=n;i++)
        {
            for(j=1;j<=m;j++)
            {
                if(map[i][j]=='W'&&!vis[i][j])
                {
                    ans++;
                    dfs(i,j);
                }
            }
        }
        printf("%d\n",ans);
    }
}

//

DFS

转载于:https://www.cnblogs.com/java20130725/archive/2012/11/27/3215882.html

你可能感兴趣的文章
我和Django那些事儿(7)----debug设置成false后再说静态文件
查看>>
Java操作MySQL应用实例
查看>>
Java 数据库操作类
查看>>
快速切换公司双线网络的批处理文件
查看>>
登录之后更新导航
查看>>
SharePoint【ECMAScript对象模型系列】-- 01. ECMAScript对象模型的引入
查看>>
离线数据分析流程介绍
查看>>
2012-08-06
查看>>
Tips of windows mobile development
查看>>
严重: Catalina.stop: java.net.ConnectException: Connection refused: connect
查看>>
PAT 乙级 1033
查看>>
java的守护线程与非守护线程
查看>>
java排序算法
查看>>
XML 命名空间
查看>>
Linux文件系统基本结构
查看>>
九度oj 题目1438:最小公倍数
查看>>
Cocos2dx.3x入门三部曲-Hello Game项目解析(三)
查看>>
EL表达式
查看>>
git学习(2)----入门
查看>>
FINS/TCP_OMRON(1)
查看>>