POJ 2386 Lake Counting(深搜)
Lake Counting
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
思路
从任意的W开始,不停地把邻接的部分用'.'代替。 1次DFS后与初始的这个W连接的所有W就都被替
换成了'.',因此直到图中不再存在W为止,总共进行DFS的次数就是答案了。 8个方向共对应了8种
状态转移,每个格子作为DFS的参数至多被调用一次,所以复杂度为O(8×N×M)=O(N×M)。
#include<stdio.h> #define MAX_N 105 #define MAX_M 105 char field[MAX_N][MAX_M]; int N,M; void dfs(int x,int y) { int dx,dy,nx,ny; field[x][y] = '.'; //将现在位置替换为'.'; for (dx = -1;dx < 2;dx++) //遍历移动的8个方向 { for (dy = -1;dy < 2;dy++) { nx = x + dx,ny = y + dy; if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W') { //判断(nx,ny)是不是在园子内 dfs(nx,ny); } } } } int main() { int i,j,res = 0; char tmp; scanf("%d%d",&N,&M); getchar(); for (i=0;i<N;i++) { for (j=0;j<M;j++) { scanf("%c",&field[i][j]); if (j==M-1) { scanf("%c",&tmp); } } } for (i = 0;i < N;i++) { for (j = 0;j < M;j++) { if (field[i][j] == 'W') { dfs(i,j); res++; } } } printf("%d\n",res); return 0; }
- Linux内核中Netfilter架构介绍http://blog.csdn.net/wuruixn/article/details/7957368
- ScrollView嵌套ViewPager滑动冲突的解决
- 监控指定进程
- levelDB跳表实现
- PHP-004
- Building microservices with Spring Cloud and Netflix OSS, part 2
- POJ 2386 Lake Counting(深搜)
- sqlite加密
- linux hosts文件的修改------利用root权限来vim /etc/hosts
- 2016-3-2
- 补一个
- 25种提高网页加载速度的方法和技巧
- Unity3D项目之《坦克大战》
- Spark学习笔记10-RDD(Resilient Distributed Datasets)
- jsp指令标识
- spring MVC配置详解
- CSDN-markdown编辑器的使用
- 144. Binary Tree Preorder Traversal &&94. Binary Tree Inorder Traversal
- 运算符和表达式
- 【杭电oj】1873 - 看病要排队(优先队列,水)