通過對堆棧和隊列的學習,以《數據結構與算法-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();
}
}
