[問題] 請問老鼠走迷宮碰到三叉路時如何判斷?
開發平台(Platform): (Ex: VC++, Gcc, Linux, ...)
C++
問題(Question):
現在程式可以跑,但到三叉路那段會有路走不到,求解
程式碼(Code): (請善用置底文標色功能)
#include <stdio.h>
#include <stdlib.h>
#include "stack.c"
/* 主程式: 使用回溯方法在陣列走迷宮 */
int main() {
int maze[11][10] = { /* 迷宮陣列,數字0可走, 1不可走 */
1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 0, 1, 1, 1, 1,
1, 1, 1, 0, 0, 0, 0, 1, 1, 1,
1, 1, 1, 0, 1, 0, 1, 1, 1, 1,
1, 0, 0, 0, 1, 0, 0, 0, 0, 1,
1, 1, 1, 0, 1, 1, 1, 1, 1, 1,
1, 1, 1, 0, 1, 0, 0, 0, 0, 1,
1, 1, 1, 0, 0, 0, 1, 1, 1, 1,
1, 1, 1, 1, 1, 0, 0, 0, 1, 1,
1, 1, 1, 1, 1, 1, 1, 1, 1, 1 };
int i,j;
int x = 5; /* 迷宮入口座標 */
int y = 1;
while ( x != 7 || y != 8 ) { /* 終點的位置*/
maze[x][y] = 2; /* 標示為已走過的路 */
if ( maze[x-1][y] <= 0 ) { /* 往上方走 */
x = x - 1; /* 座標x減1 */
push(x); /* 存入路徑 */
push(y);
}
else if ( maze[x+1][y] <= 0 ) { /* 往下方走 */
x = x + 1; /* 座標x加1 */
push(x); /* 存入路徑 */
push(y);
}
else if ( maze[x][y-1] <= 0 ) { /* 往左方走 */
y = y - 1; /* 座標y減1 */
push(x); /* 存入路徑 */
push(y);
}
else if ( maze[x][y+1] <= 0 ) {/* 往右方走 */
y = y + 1; /* 座標y加1 */
push(x); /* 存入路徑 */
push(y);
}
else { /* 沒有路可走:迴溯 */
maze[x][y] = 3; /* 表示是迴溯的路 */
y = pop(); /* 退回一步 */
x = pop();
}
}
maze[x][y] = 9; /* 標示最後位置 */
printf("迷宮路徑圖(從左到右): \n");
for ( i = 0; i <= 10; i++) { /* 顯示迷宮圖形 */
for ( j = 0; j <= 9; j++)
printf("%d ", maze[i][j]); /* 顯示座標值 */
printf("\n");
}
printf("\n數字 1: 牆壁\n數字 2: 走過的路徑\n");
printf("數字 3: 回溯路徑\n");
system("PAUSE");
return 0;
}
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 123.195.32.76
推
12/30 18:35, , 1F
12/30 18:35, 1F
推
12/30 18:40, , 2F
12/30 18:40, 2F
→
12/30 19:09, , 3F
12/30 19:09, 3F
→
12/30 19:10, , 4F
12/30 19:10, 4F
→
12/30 19:11, , 5F
12/30 19:11, 5F
→
12/30 19:14, , 6F
12/30 19:14, 6F
→
12/30 19:17, , 7F
12/30 19:17, 7F
→
12/30 19:18, , 8F
12/30 19:18, 8F
→
12/30 19:20, , 9F
12/30 19:20, 9F
→
12/30 19:20, , 10F
12/30 19:20, 10F
→
12/30 19:44, , 11F
12/30 19:44, 11F
推
12/30 23:14, , 12F
12/30 23:14, 12F
→
12/30 23:25, , 13F
12/30 23:25, 13F
→
12/30 23:32, , 14F
12/30 23:32, 14F
推
01/02 21:06, , 15F
01/02 21:06, 15F
→
01/02 21:09, , 16F
01/02 21:09, 16F