poj 2386:Lake Counting(简单DFS深搜)
2024-08-26 05:02:18
Lake Counting
Time Limit: 1000MS | Memory Limit: 65536K | |
Total Submissions: 18201 | Accepted: 9192 |
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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
Source
简单深搜。
遍历迷宫中所有的点,如果是‘W’,开始dfs搜索,将它临近的八个方向是‘W’的点全部走遍,并将走过的点变为‘.’,这样这一块‘W’区域就全部走完。一共走过了多少个这样的区域,就是结果。
代码:
#include <iostream> using namespace std;
int n,m;
char a[][];
int dx[] = {,,,,,-,-,-}; //八个方向
int dy[] = {,,,-,-,-,,};
bool judge(int x,int y)
{
if(x< || x>n || y< || y>m)
return ;
if(a[x][y]!='W')
return ;
return ;
}
void dfs(int x,int y)
{
a[x][y] = '.'; //将‘W’转化为‘.’
for(int i=;i<;i++){
int nx = x + dx[i];
int ny = y + dy[i];
//如果这一步是‘W’,且没有越界,可以走。
if(judge(nx,ny))
continue;
dfs(nx,ny);
}
}
int main()
{
while(cin>>n>>m){
int sum = ;
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
cin>>a[i][j];
for(int i=;i<=n;i++)
for(int j=;j<=m;j++)
if(a[i][j]=='W'){
sum++;
dfs(i,j);
}
cout<<sum<<endl;
}
return ;
}
Freecode : www.cnblogs.com/yym2013
最新文章
- W3School-CSS 背景实例
- android selector(转)
- 如何查看JSP和Servlet版本
- [转] Android PhoneGap Cordova 体系结构
- MySQL忘记root密码--skip-grant-tables
- 关于Git远程版本库
- cygwin在Windows8.1中设置ssh的问题解决
- win10的MySQL客户端连接centos7虚拟机的mysql服务端连接不上解决办法
- Linux中对逻辑卷的移除
- textarea高度自适应自动展开
- Python scipy 计算短时傅里叶变换(Short-time Fourier transforms)
- 大数据开发实战:Spark Streaming流计算开发
- JSP共享javabean
- BZOJ 1014 [JSOI2008]火星人prefix (Splay + Hash + 二分)
- cocos2d-x3.0 Slider
- Java WebService 简单实例(转
- Linux目录与文件操作
- java四种访问权限
- 十二.spring-boot使用spring-boot-freemarker
- mac用ssh连接linux云服务器中文乱码或无法显示解决