简单深度优先搜索
来源:互联网 发布:unity3d unreal4 比较 编辑:程序博客网 时间:2024/06/06 19:51
深度优先遍历过程。
从一个点向下试,直到试不下去为止。
图与树不同,树从一个根开始,向下走,一定有走不下去的时候,而图存在环,为此,需要记录每一个点是否被遍历过了,如果被遍历过,在下面的遍历中就不需要走了,当没有相邻节点时,就退回。
假设迷宫有5行4列
二维数组0表示空地 1表示障碍物,入口为0,0
步数最少到达3,2
//深度优先搜索迷宫问题public class Dfs { int p; int q; int min =Integer.MAX_VALUE; int m; int n; int book[][] = new int [50][50]; int next[][] ={{0,1},{1,0},{0,-1},{-1,0}}; int a[][]; /** * @return the min */ public int getMin() { return min; } /** * @param min the min to set */ public void setMin(int min) { this.min = min; } /** * @return the p */ public int getP() { return p; } /** * @param p the p to set */ public void setP(int p) { this.p = p; } /** * @return the q */ public int getQ() { return q; } /** * @param q the q to set */ public void setQ(int q) { this.q = q; } /** * @return the m */ public int getM() { return m; } /** * @param m the m to set */ public void setM(int m) { this.m = m; } /** * @return the n */ public int getN() { return n; } /** * @param n the n to set */ public void setN(int n) { this.n = n; } /** * @return the a */ public int[][] getA() { return a; } /** * @param a the a to set */ public void setA(int[][] a) { this.a = a; } public void dfs(int x,int y,int step){ int tx; int ty; int k; if(x==p-1&&y==q-1){ if(step<min){ min = step; setMin(min); } return ; } for( k=0;k<4;k++){ tx=x+next[k][0]; ty=y+next[k][1]; if(tx>=m||ty>=n||tx<0||ty<0) { continue; } if(book[x][y]==0&&a[x][y]==0){ book[x][y] =1; dfs(tx,ty,step+1); book[x][y] =0; } } return; } public static void main(String[] args) { Dfs dfs = new Dfs(); int a[][]={{0,0,1,0},{0,0,0,0},{0,0,1,0},{0,1,0,0},{0,0,0,1}}; dfs.setA(a); dfs.setM(5); dfs.setN(4); dfs.setP(4); dfs.setQ(3); dfs.dfs(0, 0, 0); System.out.println(dfs.getMin()); }}
0 0
- 简单深度优先搜索
- 深度优先搜索简单入门
- 简单的深度优先搜索HDU1045
- 简单介绍深度优先和广度优先搜索
- DFS深度优先搜索(5)--poj1579(简单记忆化搜索)
- 搜索算法简单介绍:回溯法,深度优先搜索,广度优先搜索
- 深度优先搜索
- 深度优先搜索
- 深度优先搜索 DFS
- 深度优先搜索遍历
- 深度优先搜索 DFS
- 深度优先搜索
- 深度优先搜索
- 深度优先搜索算法
- hdoj1015Safecracker(深度优先搜索)
- [AI]深度优先搜索
- 深度优先搜索算法
- DFS 深度优先搜索
- SpringBoot之添加单元测试
- 使用面向对象技术替代switch-case和if-else
- 永远不要批评、指责、抱怨别人
- Docker tf image on Win
- 关于Centos服务器上Oracle XE 远程访问设置
- 简单深度优先搜索
- Android中Http网络请求响应基本知识
- 搜索——I’m stuck!(ccf)
- VS调试ASP.NET MVC程序出现"未连接到互联网"的解决方法
- latex编排论文经验1
- Android中OkHttp使用手册
- AsyncTask源码分析
- C#-static
- 第12周 项目5 迷宫问题(利用深度遍历算法)