原因:scanf("%d", &maze[x][y]) 讀取整數,但迷宮數據為字符 '0' '1',格式不匹配導致緩衝區殘留,後續讀取失敗。
修復:改用字符讀取:
char ch;
scanf(" %c", &ch); // 空格跳過空白字符
maze[x][y] = ch;
原因:外層 while(d==1),內部 scanf("%d", &d) 讀取重試選擇,但若輸入非數字,d 不更新,緩衝區殘留導致無限循環。
修復:輸入驗證 + 緩衝區清理:
int retry;
do {
printf("重試? 1/0: ");
while (scanf("%d", &retry) != 1 || (retry != 0 && retry != 1)) {
printf("輸入 0 或 1: ");
while (getchar() != '\n'); // 清理緩衝區
}
d = retry;
} while (d == 1);
控制台無法畫線。方案:
─ │ ┌ ┐ └ ┘ ├ ┤ ┬ ┴ ┼ 盒繪字符)SetConsoleCursorPosition + 彩色字符標記路徑
#include
#include
// ... 迷宮邏輯 ...
initgraph(640, 480);
setlinecolor(RED);
setlinestyle(PS_SOLID, 3);
for (int i = 0; i < pathLen - 1; i++) {
line(path[i].y*CELL_SIZE + CELL_SIZE/2, path[i].x*CELL_SIZE + CELL_SIZE/2,
path[i+1].y*CELL_SIZE + CELL_SIZE/2, path[i+1].x*CELL_SIZE + CELL_SIZE/2);
}
getch(); closegraph();
int dx[4]={0,1,0,-1}, dy[4]={1,0,-1,0} (右下左上)visited 數組,不破壞原迷宮