程序设计:院子积水问题Lake Counting
来源:互联网 发布:科研设计 软件 编辑:程序博客网 时间:2024/04/28 02:15
Lake Counting
原英文描述:
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.
思路:
采用深度优先(DFS)的方法,可以从任意的 W 开始,不停地把邻接的W部分用 ‘.’ 代替。1次DFS后与初始的这个 W 连接的所有 W 就都被替换成了 ‘.’ ,因此直到图中不再存在 W 为止,总共进行DFS的次数就是答案了。8个方向共对应了8种状态转移,每个格子作为DFS的参数至多被调用一次,所以复杂度为O(8×N×M)=O(N×M)。
代码部分:
// 输入int N, M;char field[MAX_N][MAX_M + 1]; // 园子// 现在位置(x,y)void dfs(int x, int y) {// 将现在所在位置替换为.field[x][y] = '.';// 循环遍历移动的8个方向for (int dx = -1; dx <= 1; dx++) { for (int dy = -1; dy <= 1; dy++) {// 向x方向移动dx,向y方向移动dy,移动的结果为(nx,ny)int nx = x + dx, ny = y + dy;// 判断(nx,ny)是不是在园子内,以及是否有积水if (0 <= nx && nx < N && 0 <= ny && ny < M && field[nx][ny] == 'W') dfs(nx, ny); }}return ;}void solve() {int res = 0;for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { if (field[i][j] == 'W') { // 从有W的地方开始dfs dfs(i, j); res++; } }}printf("%d\n", res);}
0 0
- 程序设计:院子积水问题Lake Counting
- 搜索入门(DFS)-Lake Counting(积水连通问题)
- Lake Counting (简单深搜)积水问题
- //判断院子里是否有积水
- Lake Counting
- Lake Counting
- Lake Counting
- Lake Counting
- Lake Counting
- lake counting
- Lake Counting
- Lake Counting
- Lake Counting
- Lake counting
- Lake Counting
- Lake Counting
- Lake Counting
- Lake Counting
- makefile中命令写在两行和写在一行的区别
- 打印棱形星星
- zend studio自动提示调整
- opencv光影删除法去除背景
- mybatis简单crud
- 程序设计:院子积水问题Lake Counting
- Gradle学习笔记(二)构建脚本
- LintCode:动态规划 爬楼梯
- 使用PyCharm进行远程开发和调试
- JAVA个人学习路线
- lightpoj-【February 29】
- HDU 5550 dp + 前缀和优化
- 自卑与超越—读书笔记
- 【利器】使用rsync进行主机间数据同步