#include#include#include#include#includeusing namespace std;typedef struct Point{int i;int j;}Point;class Maze//迷宫类{public:Maze(){node.i = 1;node.j = 0;goal.i = 8;goal.j = 9;FILE *maze_map;errno_t error;error = fopen_s(&maze_map,"maze.txt", "r");if (error != 0)//返回0表示文件打开成功{printf("Error!\n");return;}char ch;for (int i = 0; i < 10; i++)//赋值地图{for (int j = 0; j < 10; j++){while (1){ch = fgetc(maze_map);if (ch != ' ' && ch!='\n'){map[i][j] = ch;break;}}}}//free(maze_map);//释放指针}void Route()//路径 通路为'0',墙壁为'1'{map[node.i][node.j] = '2';//当走过某一路径后该路径被标为'2'PrintMaze();printf("\n点击开始\n");system("pause");while (1)//判断上下左右有无通路,若有同路则压入栈,没有则退回至上一步{system("CLS");if (map[node.i - 1][node.j] == '0' && (node.i-1) >= 0)//up{node.i--;route.push(node);map[node.i][node.j] = '2';}else if (map[node.i + 1][node.j] == '0' && (node.i+1) <= 9)//down{node.i++;route.push(node);map[node.i][node.j] = '2';}else if (map[node.i][node.j - 1] == '0' && (node.j-1) >= 0)//left{node.j--;route.push(node);map[node.i][node.j] = '2';}else if (map[node.i][node.j + 1] == '0' && (node.j+1) <= 9)//right{node.j++;route.push(node);map[node.i][node.j] = '2';}else//noway{node = route.top();//此处if()为避免十字路口处有通路但十字路口却已经被pop而无法行进的情况if (map[node.i - 1][node.j] != '0' && map[node.i + 1][node.j] != '0' && map[node.i][node.j - 1] != '0' && map[node.i][node.j + 1] != '0'){route.pop();}if (route.empty()){printf("该迷宫没有通路\n");break;}}if ((node.i == goal.i) && (node.j == goal.j))//判断是否到终点{system("CLS");PrintMaze();printf("\n到达终点!!\n");break;}PrintMaze();printf("\n%d,%d", node.i, node.j);//system("pause");Sleep(100);}}void PrintMaze()//打印地图及位置{for (int i = 0; i < 10; i++){for (int j = 0; j < 10; j++){if (map[i][j] == '1')printf("■");else if (i == node.i && j == node.j)printf("○");elseprintf(" ");}printf(" ");for (int k = 0; k < 10; k++){printf(" %c",map[i][k]);}printf("\n");}}~Maze(){}private:char map[10][10];stack route;Point node;//位置Point goal;//终点};void Test(){Maze _maze;_maze.Route();}int main(){Test();return 0;}
【迷宫】【C++】无递归无路径判优
最新推荐文章于 2023-06-11 20:32:19 发布