
【例 3-22】 采用队列的迷宫算法 页码P61
package hicc.ds.c02_linear2;
import java.util.Arrays;
class Sign {
int x, y;
int pre;
@Override
public String toString() {
return "(" + x + ", " + y + ", " + pre + ")";
}
}
public class QueueSolveMaze {
private int m = 6;
private int n = 8;
public int path(int[][] maze, Item[] move) {
Sign[] sq = new Sign[m*n];
for (int i = 0; i < sq.length; i++) {
sq[i] = new Sign();
}
int front, rear;
int x, y, i, j, v;
front = rear = 0;
sq[0].x = 1;
sq[0].y = 1;
sq[0].pre = -1;
maze[1][1] = -1;
while (front <= rear) {
x = sq[front].x;
y = sq[front].y;
for (v = 0; v < 8; v++) {
i = x + move[v].x;
j = y + move[v].y;
if (maze[i][j] == 0) {
rear++;
sq[rear].x =i;
sq[rear].y =j;
sq[rear].pre = front;
System.out.println(Arrays.toString(sq));
maze[i][j] = -1;
}
if (i == m && j == n) {
printPath(sq, rear);
return 1;
}
}
front++;
}
return 0;
}
public void printPath(Sign[] sq, int rear) {
do {
System.out.println(sq[rear]);
rear = sq[rear].pre;
} while (rear != -1);
}
public static void main(String[] args) {
int[][] maze = new int[][] {
// 0, 1, 2, 3, 4, 5, 6, 7, 8, 9
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, //0
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 }, //1
{ 1, 1, 0, 1, 0, 1, 1, 1, 1, 1 }, //2
{ 1, 0, 1, 0, 0, 0, 0, 0, 1, 1 }, //3
{ 1, 0, 1, 1, 1, 0, 1, 1, 1, 1 }, //4
{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 1 }, //5
{ 1, 0, 1, 1, 0, 0, 1, 1, 0, 1 }, //6
{ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, //7
};
Item[] move = new Item[] { new Item(0, 1), new Item(1, 1), new Item(1, 0), new Item(1, -1), new Item(0, -1),
new Item(-1, -1), new Item(-1, 0), new Item(-1, 1) };
QueueSolveMaze queueSolveMaze = new QueueSolveMaze();
queueSolveMaze.path(maze, move);
}
}
本文介绍了一种使用队列实现的迷宫求解算法,通过遍历迷宫并记录路径,最终找到从起点到终点的路线。算法首先将起点加入队列,并标记为已访问,然后进入循环,从队列中取出元素,检查其四周是否可以行走,若可以,则将其加入队列并标记为已访问,同时记录前驱节点。当遇到终点时,算法结束并逆向打印出路径。
1960

被折叠的 条评论
为什么被折叠?



