本文为大家分享了使用栈的迷宫算法java版,主要考察栈的使用,供大家参考,具体内容如下
主要思路如下:
do { if(当前位置可通过) { 标记此位置已走过; 保存当前位置并入栈; if(当前位置为终点) { 程序结束; } 获取下一个位置; } else { if(栈非空) { 出栈; while(当前位置方向为4且栈非空) { 标记当前位置不可走; 出栈; } if(当前位置的方向小于4) { 方向+1; 重新入栈; 获取下一个位置; } } } } while (栈非空);
java代码如下:
import java.util.Stack; public class Maze { // 栈 private Stackstack = new Stack (); // 迷宫 private int[][] maze = { {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, {1,0,1,0,0,0,1,1,0,0,0,1,1,1,1,1,1}, {1,0,0,0,0,1,1,0,1,1,1,0,0,1,1,1,1}, {1,0,1,1,0,0,0,0,1,1,1,1,0,0,1,1,1}, {1,1,1,0,0,1,1,1,1,1,1,0,1,1,0,0,1}, {1,1,0,0,1,0,0,1,0,1,1,1,1,1,1,1,1}, {1,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,1}, {1,0,0,1,1,1,1,1,1,0,1,0,0,1,0,1,1}, {1,0,1,1,1,0,0,0,0,1,1,1,1,1,1,1,1}, {1,0,0,1,1,0,1,1,0,1,1,1,1,1,0,1,1}, {1,1,0,0,0,0,1,1,0,1,0,0,0,0,0,0,1}, {1,1,0,1,1,1,1,1,0,0,0,1,1,1,1,0,1}, {1,0,0,0,0,1,1,1,1,1,0,1,1,1,1,0,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}, }; // 标记路径是否已走过 private int[][] mark = new int[MAZE_SIZE_X][MAZE_SIZE_Y]; private static final int MAZE_SIZE_X = 14; private static final int MAZE_SIZE_Y = 17; private static final int END_X = 12; private static final int END_Y = 15; private void initMark() { for (int i = 0; i
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。