【例 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);
}
}