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

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

Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 35139   Accepted: 17450

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

USACO 2004 November

问题链接:。

题意简述:给定m×n矩阵 (1 <= N <= 100; 1 <= M <= 100),其中'W'代表水域,'.'代表陆地,问有几片湖。

本题可以使用深度优先搜索求解,用广度优先搜索也可以求解,差别不大。

问题分析这个题》完全相同,程序改两个字符,改了一下结束条件就通过了。

程序说明

程序中的有关内容说明如下:

1.方向数组 使用方向数组后,各个方向的试探的程序就会变得简洁了,用循环处理即可。

2.避免重复搜索 将搜索过的节点设置为'.'(陆地),可以避免重复搜索,能够简化程序逻辑。

3.设置边界 通过设置边界,可以免去矩阵(二维数组)的边界判断,简化了程序逻辑。

该问题与图遍历中寻找联通块问题基本上是同构的,算法思路一致。

每当找到一个水域,只需要计数加一,并且使用DFS算法把与其相邻的8个水域擦除即可(避免重复计数)。

参考链接

AC的C语言程序如下:

/* POJ2386 Lake Counting */#include 
#include
#define DIRECTSIZE 8struct direct { int drow; int dcol;} direct[DIRECTSIZE] = {
{0, -1}, {0, 1}, {-1, 0}, {1, 0}, {-1, -1}, {-1, 1}, {1, -1}, {1, 1}};#define MAXN 100char grid[MAXN+2][MAXN+2];void dfs(int row, int col){ int i; for(i=0; i

转载于:https://www.cnblogs.com/tigerisland/p/7564414.html

你可能感兴趣的文章
Python 爬虫十六式 - 第六式:JQuery的假兄弟-pyquery
查看>>
宜昌a货翡翠,包头a货翡翠
查看>>
【微信事业群】趣味面试算法题
查看>>
保守的国美再一次进击社交电商,前途未卜?
查看>>
git
查看>>
Python学习教程(Python学习路线):Python 3—手动创建迭代器
查看>>
说说如何在 Virtual Box 中新建 CentOS 虚拟机
查看>>
Cordova + Vue 实现点击两次退出应用
查看>>
JAVA 多用户商城系统b2b2c-Spring Cloud Stream 介绍
查看>>
spring cloud构建互联网分布式微服务云平台-SpringCloud集成项目简介
查看>>
基于房源的画像分析
查看>>
80% UI 初学者走过的弯路,你走了几条?
查看>>
文档和元素的几何滚动
查看>>
php 设计模式
查看>>
Java springcloud B2B2C o2o多用户商城 springcloud架构(八)springboot整合mongodb
查看>>
3年工作经验的Java程序员面试经过
查看>>
Mysql 批量写入数据,对于这类性能问题,你是如何优化的
查看>>
MySQL无法启动几种常见问题小结
查看>>
阿里CTO:阿里所有技术和产品输出都将必须通过阿里云进行
查看>>
更好用的集群限流功能,Sentinel 发布 v1.4.2
查看>>