C语言迷宫求解代码解析:带注释的示例
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <conio.h> #include <windows.h>
#define WIDTH 10 #define HEIGHT 10
typedef struct { int x, y; } Point;
// 迷宫地图 char map[HEIGHT][WIDTH] = { {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}, {'#', ' ', ' ', ' ', '#', ' ', ' ', ' ', ' ', '#'}, {'#', ' ', '#', ' ', '#', ' ', '#', '#', ' ', '#'}, {'#', ' ', '#', ' ', ' ', ' ', ' ', '#', ' ', '#'}, {'#', ' ', '#', '#', '#', '#', ' ', '#', ' ', '#'}, {'#', ' ', ' ', ' ', ' ', '#', ' ', '#', ' ', '#'}, {'#', '#', '#', '#', ' ', '#', ' ', '#', ' ', '#'}, {'#', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '#'}, {'#', ' ', '#', '#', '#', '#', '#', '#', ' ', '#'}, {'#', '#', '#', '#', '#', '#', '#', '#', '#', '#'}};
void drawMaze() { system("cls"); // 清空控制台屏幕 for (int y = 0; y < HEIGHT; y++) { for (int x = 0; x < WIDTH; x++) { printf("%c", map[y][x]); // 打印迷宫地图字符 } printf("\n"); // 打印换行符 } }
bool solveMaze(int x, int y) { if (x < 0 || x >= WIDTH || y < 0 || y >= HEIGHT || map[y][x] == '#') { return false; // 到达边界或墙壁,返回失败 }
if (map[y][x] == 'G') {
return true; // 到达终点,返回成功
}
map[y][x] = '.'; // 标记当前位置为路径
drawMaze(); // 绘制迷宫地图
if (solveMaze(x + 1, y) || solveMaze(x - 1, y) || solveMaze(x, y + 1) || solveMaze(x, y - 1)) {
return true; // 尝试向四个方向继续解决迷宫,如果有一条路径成功,返回成功
}
map[y][x] = ' '; // 撤销当前位置的路径标记
drawMaze(); // 绘制迷宫地图
return false; // 四个方向都无解,返回失败
}
int main() { Point start = {1, 1};
map[start.y][start.x] = 'S'; // 设置起点位置
map[8][8] = 'G'; // 设置终点位置
drawMaze(); // 绘制迷宫地图
printf("Press any key to solve the maze...
"); getch(); // 等待用户按下任意键
if (solveMaze(start.x, start.y)) {
printf("Maze solved!
"); // 迷宫解决成功 } else { printf("No solution found. "); // 迷宫无解 }
return 0;
}
原文地址: https://www.cveoy.top/t/topic/bOpS 著作权归作者所有。请勿转载和采集!