用c语言写一个迷宫算法
时间: 2024-05-12 15:18:41 浏览: 14
好的,我可以为您提供一个基于C语言的迷宫算法的示例程序。以下是示例代码:
```
#include <stdio.h>
#include <stdlib.h>
#define ROWS 10 // 迷宫行数
#define COLS 10 // 迷宫列数
int maze[ROWS][COLS] = {
{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, 1, 1, 1, 0, 1, 1, 0, 1},
{1, 1, 0, 0, 0, 0, 0, 0, 0, 1},
{1, 1, 1, 1, 1, 1, 1, 1, 1, 1}
};
enum { UP, RIGHT, DOWN, LEFT };
struct point {
int x;
int y;
int dir;
};
struct point top = { 1, 1, LEFT };
struct point stack[100];
int top_idx = -1;
int main(int argc, char *argv[])
{
int dir, i, x, y, found = 0;
stack[++top_idx] = top;
while (top_idx != -1 && !found) {
top = stack[top_idx--];
x = top.x; y = top.y; dir = top.dir;
while (dir < 4 && !found) {
x = top.x; y = top.y; dir++;
switch (dir) {
case UP:
x--; break;
case RIGHT:
y++; break;
case DOWN:
x++; break;
case LEFT:
y--; break;
}
if (x == ROWS - 2 && y == COLS - 2)
found = 1;
else if (!maze[x][y]) {
top.dir = dir;
stack[++top_idx] = top;
top.x = x; top.y = y; top.dir = UP;
stack[++top_idx] = top;
dir = 4;
}
}
}
if (found) {
printf("The path is: \n");
printf("row col\n");
for (i = 0; i <= top_idx; i++)
printf("%2d%5d\n", stack[i].x, stack[i].y);
printf("%2d%5d\n", ROWS - 2, COLS - 2);
printf("%2d%5d\n", 1, 1);
}
else
printf("The maze does not have a path.\n");
return 0;
}
```
这是一个基本的“左手规则”迷宫求解算法示例。这个算法会按照“左手墙壁贴着走”的方式,尽可能在遇到路口时沿着左墙壁方向前进,如果无法继续前进,则返回到上一个路口并换方向继续探索。如果在遍历完整个迷宫后没有找到出口,则宣布迷宫无解。
请注意,此示例代码只能解决静态迷宫,不能解决动态迷宫。要解决动态迷宫的问题,需要使用更高级的算法。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)