《挑战》2.1 POJ 2386 Lake Counting (简单的dfs)
2015-07-25 00:08
495 查看
# include<cstdio> # include<iostream> using namespace std; # define MAX 123 char grid[MAX][MAX]; int nxt[8][2] = { {1,0},{0,-1},{-1,0},{0,1},{1,1},{1,-1},{-1,1},{-1,-1} }; int n,m; int can_move( int x,int y ) { if ( x>=0&&x<n&&y>=0&&y<m ) { if ( grid[x][y]=='W' ) return 1; } return 0; } void dfs ( int x,int y ) { grid[x][y] = '.'; for ( int i = 0;i < 8;i++ ) { int n_x = x+nxt[i][0], n_y = y+nxt[i][1]; if ( can_move(n_x,n_y) ) { dfs(n_x,n_y); } } return; } int main(void) { //int n,m; int res; while ( scanf("%d%d",&n,&m)!=EOF ) { res = 0; for ( int i = 0;i < n;i++ ) scanf("%s",grid[i]); for ( int i = 0;i < n;i++ ) { for ( int j = 0;j < m;j++ ) { if ( grid[i][j]=='W' ) { dfs(i,j); res++; } } } printf("%d\n",res); } return 0; }
A - Lake Counting
Crawling in process... Crawling failed Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
Submit Status Practice POJ 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
Hint
OUTPUT DETAILS:
There are three ponds: one in the upper left, one in the lower left,and one along the right side.
题目大意:
就是说一个n*m的网格中,求出联通块的个数。
解题思路:
就是一个dfs的基础题,从任意一个满足要求的点开始dfs,求出直到不能走动为止,res++。
复杂度:
O(8*m*n)
代码:
相关文章推荐
- linux-kernel doc (memory-hotplug)
- 写程序的时候, 我们想关注什么
- 《你的时间有限,不要为别人而活》句子摘选
- 好牛批的对联
- 枚举 hdu1172 猜数字
- KVM 【SNAT/DNAT2种配置实现以及扁平化网络模式(flat)实现/virsh2种动态迁移实现】
- KVM 【SNAT/DNAT2种配置实现以及扁平化网络模式(flat)实现/virsh2种动态迁移实现】 分类: Linux kvm 网络通讯 2015-07-25 00:05 322人阅读 评论(0) 收藏
- 获取URL的数据
- Text Kit学习(入门和进阶)
- 2005 第几天?
- LintCode - Remove Duplicates from Sorted List II Show result
- hiho一下 连通性·四 点的双连通分量
- Linuxc 文件操作讲座知识
- linux程序设计——套接字选项(第十五章)
- 以实例简介Java中线程池的工作特点
- java多线程学习笔记——concurrent包的一些类(Lock 和Condition)
- Windows 2008 R2 64bit Apache 2.4.4 + PHP 5.5.27 配置
- 小贝_mysql分区理论学习
- 使用 IBM Bluemix 构建,部署和管理自定义应用程序
- 使用纯php代码实现页面伪静态的方法