栈应用2:走迷宫
来源:互联网 发布:xml转json 编辑:程序博客网 时间:2024/05/21 22:53
1.起点设置为-1,防止重走起点
2.顺时针遍历每一个可走的方向
3.有路可走时,该方向的结点进栈保存为路径中的一步,并将迷宫数组中该结点设置为-1,防止重走该结点
4.无路可走的时候回溯,当前结点出栈,回到2
5.重复2,3,4直到找到终点,或者遍历完无路可走。
package Migong;//迷宫class Map{ //迷宫数组,外围加一道围墙,防止数组越界出现异常 public static int mg[][] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 0, 1, 0, 0, 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1, 0, 1, 1, 0, 1 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } };}// 路径栈class Stack{ final int MaxSize = 100; int i[] = new int[MaxSize]; int j[] = new int[MaxSize]; int di[] = new int[MaxSize]; int top; public Stack() { top = -1; }}public class Main{ public static void main(String args[]) { final int M = 8; final int N = 8; mgpath(1, 1, M, N); } // 求解路径为:(xi,yi)->(xe,ye) public static void mgpath(int xi, int yi, int xe, int ye) { Stack st = new Stack(); int i, j, k, di, find; st.top++; st.i[st.top] = xi; // 初始化栈栈顶为迷宫入口 st.j[st.top] = yi; st.di[st.top] = -1; Map.mg[xi][yi] = -1; // 标示迷宫入口 while (st.top > -1) { i = st.i[st.top]; j = st.j[st.top]; di = st.di[st.top]; if (i == xe && j == ye) // 走到终点 { System.out.println("迷宫路径如下:"); for (k = 0; k <= st.top; k++) { System.out.print("(" + st.i[k] + "," + st.j[k] + ") "); if ((k + 1) % 5 == 0) System.out.println(); } System.out.println(); return; } find = 0; while (di < 4 && find == 0) // 顺时针查找该点周围四个方向的出路 { di++; switch (di) { case 0: // 0点 (i-1,j) i = st.i[st.top] - 1; j = st.j[st.top]; break; case 1: // 1点(i,j+1) i = st.i[st.top]; j = st.j[st.top] + 1; break; case 2: // 2点(i+1,j) i = st.i[st.top] + 1; j = st.j[st.top]; break; case 3: // 3点(i,j-1) i = st.i[st.top]; j = st.j[st.top] - 1; break; } if (Map.mg[i][j] == 0) // 该点路可以走,find=1表示找到路径 find = 1; } if (find == 1) // 有路可走 { st.di[st.top] = di; st.top++; st.i[st.top] = i; // 将该路结点进栈 st.j[st.top] = j; st.di[st.top] = -1; Map.mg[i][j] = -1; // 将该结点置-1防止重走 } else // 无路可走 将结点退栈 { Map.mg[st.i[st.top]][st.j[st.top]] = 0; // 将该结点置为可走 st.top--; } } System.out.println("No Way"); }}
输出:
迷宫路径如下:
(1,1) (1,2) (2,2) (3,2) (3,1)
(4,1) (5,1) (5,2) (5,3) (6,3)
(6,4) (6,5) (5,5) (4,5) (4,6)
(4,7) (3,7) (3,8) (4,8) (5,8)
(6,8) (7,8) (8,8)
0 0
- 栈应用2:走迷宫
- 栈应用-走迷宫
- BFS的应用-走迷宫
- 老鼠走迷宫【2】
- BNU 走迷宫2
- 6.4.2走迷宫
- 走迷宫2
- bnu1055 走迷宫2
- 16 - 12 - 21 栈的应用实例(走迷宫)
- 深度优先搜索应用:走迷宫
- 走迷宫-栈的使用
- 老鼠走迷宫 (栈实现)
- 用栈实现走迷宫
- 走迷宫函数_v0.2
- 走迷宫
- 走迷宫
- 走迷宫
- 走迷宫
- Mybatis 和 Spring 的整合
- spring上下文辅助类
- SecureCRT中文乱码解决方法
- 设备检测,手机建站框架
- java进阶-创建和销毁对象3
- 栈应用2:走迷宫
- 配置JQuery与其它库的兼容性
- 登录RAC One Node
- 抓取网页时,常用到的正则语法。(持续更新,本次2015-11-11)
- zookeeper简单配置使用
- 自定义控件(11)---Canvas的平移、旋转、缩放、错切、Matrix直接变换Canvas
- 移动硬盘“脱机”(签名冲突)的硬盘如何正常使用
- Java word文件创建
- int 和integer的误用导致 listview的不刷新