数据结构(Java版)(第3版)叶核亚 答案之用队列编迷宫(部分1)

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

//用队列:

public class Maze {

public int[][] maze = null;

public int[] xx = { 1, 0, -1, 0 };

public int[] yy = { 0, 1, 0, -1 };

public Queue queue = null;

public Maze(int[][] maze) {

this.maze = maze;

queue = new Queue(maze.length * maze.length);

}

public void go() {

Point outPt = new Point(4, 5);

Point curPt = new Point(0, 0);

Node curNode = new Node(curPt, null);

maze[curPt.x][curPt.y] = 2;

queue.entryQ(curNode);

while (!queue.isEmpty()) {

curNode = queue.outQ();

for (int i = 0; i < xx.length; ++i) {

Point nextPt = new Point();

nextPt.x = (curNode.point).x + xx[i];

nextPt.y = (curNode.point).y + yy[i];

if (check(nextPt)) {

Node nextNode = new Node(nextPt, curNode);

queue.entryQ(nextNode);

maze[nextPt.x][nextPt.y] = 2;

if (nextPt.equals(outPt)) { //判断是否到达终点

Queue storeQueue=new Queue(maze.length * maze.length);

storeQueue.entryQ(nextNode);

while ((curNode = nextNode.previous) != null) {

nextNode = curNode;

storeQueue.entryQ(curNode);

}

System.out.println("A Path is:");

while (!storeQueue.isEmpty()) {

curNode = storeQueue.outQ(); //出栈

System.out.println(curNode.point);

}

return;

}

}

}

}

System.out.println("Non solution!");

}

public boolean check(Point p) {

if (p.x < 0 || p.x >= maze.length || p.y < 0 || p.y >= maze[0].length) { return false;

}

if (maze[p.x][p.y] != 0) {

return false;

}

return true;

}

public static void main(String[] args) {

int[][] maze = {

{ 0, 1, 0, 0, 0, 1 },

{ 0, 0, 0, 1, 0, 1 },

{ 1, 0, 1, 0, 0, 1 },

{ 0, 0, 0, 1, 1, 1 },

{ 0, 1, 1, 0, 0, 0 },

{ 0, 0, 0, 0, 1, 1 },

};

new Maze(maze).go();

}

}

相关文档
最新文档