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

最新文章

  1. W3School-CSS 背景实例
  2. android selector(转)
  3. 如何查看JSP和Servlet版本
  4. [转] Android PhoneGap Cordova 体系结构
  5. MySQL忘记root密码--skip-grant-tables
  6. 关于Git远程版本库
  7. cygwin在Windows8.1中设置ssh的问题解决
  8. win10的MySQL客户端连接centos7虚拟机的mysql服务端连接不上解决办法
  9. Linux中对逻辑卷的移除
  10. textarea高度自适应自动展开
  11. Python scipy 计算短时傅里叶变换(Short-time Fourier transforms)
  12. 大数据开发实战:Spark Streaming流计算开发
  13. JSP共享javabean
  14. BZOJ 1014 [JSOI2008]火星人prefix (Splay + Hash + 二分)
  15. cocos2d-x3.0 Slider
  16. Java WebService 简单实例(转
  17. Linux目录与文件操作
  18. java四种访问权限
  19. 十二.spring-boot使用spring-boot-freemarker
  20. mac用ssh连接linux云服务器中文乱码或无法显示解决

热门文章

  1. iOS 使用NSUserdefault 保存自定义的 对象
  2. C、C++中如何成功嵌入python
  3. TP框架模板中默认值输出
  4. vpngate 的使用
  5. jumpserver v0.5.0 创建用户和管理机器
  6. phpexcel表的一些设置
  7. C# 递归查找文件夹下所有文件和子文件夹的所有文件
  8. c# 读取文件流
  9. ios 微信开发
  10. django如何修改开发服务器的端口