深度优先搜索的用法——lake counting
2015-01-10 00:00
267 查看
深度优先搜索的用法——lake counting
Java
问题主题:Lake Counting |
问题描述: 有一个大小为N*M的园子,雨后积了很多水。八连通的积水被认为是在一起的。请求出园子里共有多少个水洼?(八连通是指下图中相对+的*部分) +++ +*+ +++ 限制条件: N,M <= 100 |
样例: 输入 N=10, M=12 园子如下图(‘+’表示积水,’*’表示没有积水) +********++* *+++*****+++ ****++***++* *********++* *********+** **+******+** *+*+*****++* +*+*+*****+* *+*+******+* **+*******+* 输出 3 |
【解法一】
解题分析:
从任意的’+’开始,不停地把邻接的部分用’*’代替,一次dfs(深度优先遍历)遍历后,与初始的这个+所连接的所有+都会被替换成*,因此直到图中没有+为止,总共进行dfs的次数即为积水的次数。程序实现:
C++#include "iostream" using namespace std; const int N = 10; const int M = 12; char garden [M+1] = { "+********++*", "*+++*****+++", "****++***++*", "*********++*", "*********+**", "**+******+**", "*+*+*****++*", "+*+*+*****+*", "*+*+******+*", "**+*******+*" }; void dfs(int x, int y); void solve() { int count = 0; for(int j=0; j<N; j++) { for(int i=0; i<M; i++){ if(garden[j][i] == '+') { dfs(j, i); count ++; } } } cout << count << endl; } void dfs(int y, int x) { garden[y][x] = '*'; for(int dy=y-1; dy<=y+1; dy++) { for(int dx=x-1; dx<=x+1; dx++) { if(dx >=0 && dy >= 0 && dx < M && dy < N && garden[dy][dx] == '+') { dfs(dy, dx); } } } } int main() { solve(); return 0; } |
/** * User: luoweifu * Date: 14-1-7 * Time: 下午4:53 */ public class LakeCounting { public static final int N = 10; public static final int M = 12; private String garden[] = { "+********++*", "*+++*****+++", "****++***++*", "*********++*", "*********+**", "**+******+**", "*+*+*****++*", "+*+*+*****+*", "*+*+******+*", "**+*******+*" }; public void solve() { int count = 0; for(int j=0; j<N; j++) { for(int i=0; i<M; i++){ if(garden[j].charAt(i) == '+') { dfs(j, i); count ++; } } } System.out.println(count); } public void dfs(int y, int x) { StringBuilder stringY = new StringBuilder(garden[y]); stringY.setCharAt(x, '*'); garden[y] = stringY.toString(); for(int dy=y-1; dy<=y+1; dy++) { for(int dx=x-1; dx<=x+1; dx++) { if(dx >=0 && dy >= 0 && dx < M && dy < N && garden[dy].charAt(dx) == '+') { dfs(dy, dx); } } } } public static void main(String args[]) { LakeCounting lakeCounting = new LakeCounting(); lakeCounting.solve(); } } |
相关文章推荐
- 深度优先搜索的用法——lake counting
- POJ-2386-Lake Counting(深度优先搜索初步!)
- 深度优先搜索的用法——求数组部分和
- Lake Counting --- 深度优先搜索
- 深度优先搜索和广度优先搜索
- 深度优先搜索遍历与广度优先搜索遍历
- 数据结构学习_图(1)深度优先搜索、广度优先搜索和最小生成树
- 邻接矩阵的广度优先搜索和深度优先搜索
- 深度优先搜索之拯救ice-cream
- 深度优先搜索 DFS
- 深度优先搜索与广度优先搜索
- 深度优先搜索模板(超有用的~~)
- 深度优先搜索和广度优先搜索
- 深度优先搜索
- 深度优先搜索-----DFS
- PKU 2488 深度优先搜索
- 深度优先搜索
- ACM PKU 1011 Sticks 深度优先搜索
- 深度优先搜索 DFS
- 深度优先搜索遍历与广度优先搜索遍历