Java-栈方法实现迷宫问题
来源:互联网 发布:淘宝风力灭火机价格 编辑:程序博客网 时间:2024/06/03 22:18
import java.util.Stack;public class Solution { public final int M = 6; public final int N = 8; //8*10 M+2,N+2 public int[][] maze = { {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, {1, 1, 0, 1, 0, 1, 1, 1, 1, 1}, {1, 0, 1, 0, 0, 0, 0, 0, 1, 1}, {1, 0, 1, 1, 1, 0, 1, 1, 1, 1}, {1, 1, 0, 0, 1, 1, 0, 0, 0, 1}, {1, 0, 1, 1, 0, 0, 1, 1, 0, 1}, {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} }; //8个移动方向的增量值,顺时针,东、东南、南...... public Direction directions[] = { new Direction(0, 1), //东 new Direction(1, 1), new Direction(1, 0), new Direction(1, -1), new Direction(0, -1), new Direction(-1, -1), new Direction(-1, 0), new Direction(-1, 1) }; public boolean isExit() { Stack s = new Stack(); int x, y, d; int i, j; //入口进站 s.push( new Item(1, 1, 0)); while (!s.empty()) { Item item = (Item) s.pop(); x = item.x; y = item.y; d = item.d; while (d < 8) { i = x + directions[d].x; j = y + directions[d].y; if (maze[i][j] == 0) { s.push(new Item(x, y, d)); x = i; y = j; maze[x][y] = 3;//标记,已经走过 if (x == M && y == N) return true; else { d = 0; } } else { d++; } } } return false; }}class Direction { int x, y; public Direction(int x, int y) { this.x = x; this.y = y; }}class Item { int x, y, d; public Item(int x, int y, int d) { this.x = x; this.y = y; this.d = d; }}
先贴代码,懒得上思路了,简单分析一下:
迷宫m行n列maze[m][n],0表示通,1表示不通。从一个点可以向8个方向探路,为了处理边角情况,迷宫的四周全部加一行一列,最后为maze[m+2][n+2]。
思路:
栈初始化,
将入口点push入栈,
while(栈不为空)
{
栈顶元素出站;
while(方向<8){
如果可走,入栈,求新点坐标,并赋值给当前点,如果等于出口,返回成果。否则方向=0;
否则,方向++;
}
}
阅读全文
0 0
- Java-栈方法实现迷宫问题
- 栈实现-迷宫问题
- 迷宫问题Java版本实现
- 栈实现迷宫求解问题
- Java实现A*算法解决迷宫问题
- 解迷宫问题的Java实现
- java用栈实现迷宫
- C++链栈实现迷宫问题
- 关于迷宫问题 利用栈实现
- 【数据结构】栈实现迷宫寻路问题
- 栈与递归实现迷宫问题求
- 迷宫问题求解(用栈实现)
- 队列实现迷宫问题
- C++实现迷宫问题
- 队列实现迷宫问题
- 迷宫问题--java
- java解决迷宫问题
- 迷宫问题(java)
- Day7-20.Using Java operators
- linux查看文件内容
- kali 漏洞利用metasploit
- Day7-21.Precedence
- HDU 6127 Hard challenge(几何 多校第七场)
- Java-栈方法实现迷宫问题
- NoSql数据库总览
- Day7-22.Assignment
- Mysql存储过程案例
- 数据仓库建模-维度建模基础知识
- Redis基础
- oracle sql_plan 执行计划
- Day7-23.Mathematical operators
- Android设计模式之(1)----单例模式