首先定義節點的數據類型:
//定義節點的數據結構
class Node{
int x;
int y;
Node next;
public Node(int x,int y) {
// TODO Auto-generated constructor stub
this.x=x;
this.y=y;
this.next=null;
}
}
建立一個記錄軌跡的類,完成節點的插入與刪除工作:
package com.gqx.maze;
/**
* 記錄老鼠走迷宮的路徑
* @author 郭慶興
*
*/
public class TraceRecord {
public Node first;
public Node last;
public boolean isEmpty(){
return first==null;
}
public void insert(int x,int y){
Node newNode=new Node(x, y);
if (this.isEmpty()) {
first=last=newNode;
}else {
last.next=newNode;
last=newNode;
}
}
public void delete(){
Node newNode;
if (this.isEmpty()) {
System.out.println("隊列已經空了!/n");
return;
}
newNode=first;
while (newNode.next!=last) {
newNode=newNode.next;
}
newNode.next=last.next;
last=newNode;
}
}
寫一個主程序,在一個已知的迷宮中去完成路徑的遍歷(其中‘1’代表障礙物,‘0’代表道路可行,2代表老鼠的軌跡路線):
package com.gqx.maze;
public class MazeMain {
//定義出口的坐標
private static int exit_X=8;
private static int exit_Y=10;
//聲明迷宮數組
public static int[][] maze={{1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,1,1,1,1,1,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,0,1,1,0,0,0,0,1,1},
{1,1,1,0,0,0,0,1,1,0,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,0,1,1,0,1,1,0,1,1},
{1,1,1,1,1,1,0,1,1,0,1,1},
{1,1,0,0,0,0,0,0,1,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1}
};
public static void main(String[] args) {
// TODO Auto-generated method stub
int i,j,x=1,y=1;
TraceRecord path=new TraceRecord();
System.out.println("迷宮的地圖如下:");
for (i = 0; i < 10;i ++) {
for (j = 0; j < 12 ;j++){
System.out.print(maze[i][j]);
}
System.out.println();
}
while (x<=exit_X && y<=exit_Y) {
maze[x][y]=2;
if (maze[x-1][y]==0) {
x-=1;
path.insert(x, y);
}
else if (maze[x+1][y]==0) {
x+=1;
path.insert(x, y);
}
else if (maze[x][y-1]==0) {
y-=1;
path.insert(x, y);
}
else if (maze[x][y+1]==0) {
y+=1;
path.insert(x, y);
}
else if (x==exit_X && y==exit_Y) {
break;
}
else {
maze[x][y]=2;
path.delete();
x=path.last.x;
y=path.last.y;
}
}
System.out.println("老鼠走過的路徑是:");
for (i = 0; i < 10; i++) {
for (j = 0; j < 12; j++) {
System.out.print(maze[i][j]);
}
System.out.println();
}
}
}
運行結果如圖:

