通过对堆栈和队列的学习,以《数据结构与算法-Java实现》提供的示例为结束。
问题:一只被困的老鼠试图寻路脱离迷宫。它想通过系统地尝试所有的路径逃离。如果到达了一个死胡同,它酒按照原路返回到前一个位置再试其他没有走过的路。每个地方都可以按照四个方向前进:右,左,下,上,可能导致不必要的绕道。
思路:将入口,出口,通道和墙作为“个体”进行标记,通过二维数组组成迷宫模型,依次按照上,下,左,右的顺序遍历当前点周围各点,对于可行通的点压入栈,走过的位置做新标记。为了防止老鼠“冲出迷宫”,在构建的数组周围新加一圈围墙。
样例输入:
1100
000e
00m1
Ctrl+c
程序:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Stack;
class MazeCell{
public int x,y;
public MazeCell(){
}
public MazeCell(int x,int y){
this.x=x;
this.y=y;
}
public boolean equals(MazeCell cell){
return x==cell.x&&y==cell.y;
}
}
class Maze {
private int rows=0;
private int cols=0;
private char[][] store;
private MazeCell currentCell=new MazeCell();
private MazeCell entryCell=new MazeCell();
private MazeCell exitCell=new MazeCell();
private final char exitMaker='e';
private final char entryMaker='m';
private final char visited='.';
private final char passage='0';
private final char wall='1';
private Stack mazeStack=new Stack();
public Maze(){
int row=0;//统计输入行数
int col=0;
Stack mazeRows=new Stack();
BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter a rectangular maze using the following characters:\n"+
"m-entry,e-exit,l-wall,0-passage.Enter one line at a time; end with Ctrl-z:");
try{
String str=buffer.readLine();
while(str!=null){
row++;
cols=str.length();//确定一行所含字母数
str="1"+str+"1";
mazeRows.push(str);
if(str.indexOf(entryMaker)!=-1){//确定入口的坐标
entryCell.x=row;
entryCell.y=str.indexOf(entryMaker);
}
if(str.indexOf(exitMaker)!=-1){//确定出口的坐标
exitCell.x=row;
exitCell.y=str.indexOf(exitMaker);
}
str=buffer.readLine();
}
}catch(Exception e){
e.printStackTrace();
}
rows=row;//确定行数
store=new char[rows+2][];
store[0]=new char[cols+2];
for(;!mazeRows.isEmpty();row--)
store[row]=((String)mazeRows.pop()).toCharArray();
store[rows+1]=new char[cols+2];
for(col=0;col<cols+2;col++){
store[0][col]=wall;
store[rows+1][col]=wall;
}
}
private void display(){
for(int row=0;row<=rows+1;row++)
System.out.println(store[row]);
System.out.println();
}
private void pushUnvisited(int row,int col){
if(store[row][col]==passage||store[row][col]==exitMaker)
mazeStack.push(new MazeCell(row,col));
}
public void exitMaze(){
currentCell=entryCell;
System.out.println();
while(!currentCell.equals(exitCell)){
int row=currentCell.x;
int col=currentCell.y;
display();
if(!currentCell.equals(entryCell))
store[row][col]=visited;
pushUnvisited(row-1,col);
pushUnvisited(row+1,col);
pushUnvisited(row,col-1);
pushUnvisited(row,col+1);
if(mazeStack.isEmpty()){
display();
System.out.println("Failure");
return;
}else{
currentCell=(MazeCell)mazeStack.pop();
}
}
display();
System.out.println("Success");
}
public static void main(String args[]){
(new Maze()).exitMaze();
}
}