佇列應用2:求解迷宮問題,最短路徑
輸出:package Queue; //迷宮 class Map { // 迷宮陣列,外圍加一道圍牆,防止陣列越界出現異常 public static int mg[][] = { { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }, { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, { 1, 0, 0, 1, 0, 0, 0, 1, 0, 1 }, { 1, 0, 0, 0, 0, 1, 1, 0, 0, 1 }, { 1, 0, 1, 1, 1, 0, 0, 0, 0, 1 }, { 1, 0, 0, 0, 1, 0, 0, 0, 0, 1 }, { 1, 0, 1, 0, 0, 0, 1, 0, 0, 1 }, { 1, 0, 0, 1, 1, 0, 1, 1, 0, 1 }, { 1, 0, 0, 0, 0, 0, 0, 0, 0, 1 }, { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } }; } // 路徑佇列 class Queue { final int MaxSize = 100; int i[] = new int[MaxSize]; int j[] = new int[MaxSize]; int pre[] = new int[MaxSize]; int front; int rear; public Queue() { front = -1; rear = -1; } } public class Main { public static void main(String args[]) { final int M = 8; final int N = 8; mgpath(1, 1, M, N); } // 求解路徑為:(xi,yi)->(xe,ye) public static void mgpath(int xi, int yi, int xe, int ye) { Queue q = new Queue(); int i, j, di; boolean find = false; q.rear++; q.i[q.rear] = xi; q.j[q.rear] = yi; q.pre[q.rear] = -1; Map.mg[xi][yi] = -1; // 標記入口 while (q.front <= q.rear && (!find)) { q.front++; i = q.i[q.front]; j = q.j[q.front]; if (i == xe && j == ye) { find = true; print(q,q.front); return; } for (di = 0; di < 4; di++) { switch (di) { case 0: i = q.i[q.front] - 1; j = q.j[q.front]; break; case 1: i = q.i[q.front]; j = q.j[q.front] + 1; break; case 2: i = q.i[q.front] + 1; j = q.j[q.front]; break; case 3: i = q.i[q.front]; j = q.j[q.front] - 1; } if (Map.mg[i][j] == 0) { q.rear++; q.i[q.rear] = i; q.j[q.rear] = j; q.pre[q.rear] = q.front; Map.mg[i][j] = -1; } } } System.out.println("No Way!"); } public static void print(Queue q, int front) { int k = front, j, ns = 0; System.out.println(); do // 反向找到最短路徑,並將該路徑上的方塊的成員pre設定為-1 { j = k; k = q.pre[k]; q.pre[j] = -1; } while (k != 0); System.out.println("迷宮路徑如下:"); k = 0; while (k < q.MaxSize) { if (q.pre[k] == -1) { ns++; System.out.print("(" + q.i[k] + "," + q.j[k] + ")"); if (ns % 5 == 0) System.out.println(); } k++; } System.out.println(); System.out.println("佇列狀態"); System.out.println("下標 i j pre"); for(int i=0;i<=q.rear;i++) { System.out.printf("%2d %d %d %2d\n",i,q.i[i],q.j[i],q.pre[i]); } } }
迷宮路徑如下:
(1,1)(2,1)(3,1)(4,1)(5,1)
(5,2)(5,3)(6,3)(6,4)(6,5)
(7,5)(8,5)(8,6)(8,7)(8,8)
佇列狀態
下標 i j pre
0 1 1 -1
1 1 2 0
2 2 1 -1
3 2 2 1
4 3 1 -1
5 3 2 3
6 4 1 -1
7 3 3 5
8 5 1 -1
9 3 4 7
10 5 2 -1
11 6 1 8
12 2 4 9
13 5 3 -1
14 7 1 11
15 1 4 12
16 2 5 12
17 6 3 -1
18 7 2 14
19 8 1 14
20 1 5 15
21 2 6 16
22 6 4 -1
23 8 2 18
24 1 6 20
25 6 5 -1
26 8 3 23
27 5 5 25
28 7 5 -1
29 8 4 26
30 4 5 27
31 5 6 27
32 8 5 -1
33 4 6 30
34 5 7 31
35 8 6 -1
36 4 7 33
37 5 8 34
38 6 7 34
39 8 7 -1
40 3 7 36
41 4 8 36
42 6 8 37
43 8 8 -1
44 3 8 40
45 7 8 42