利用栈写迷宫代码c语言版
时间: 2023-08-01 08:10:45 浏览: 43
以下是一个简单的迷宫求解的C语言代码,利用栈实现:
```c
#include <stdio.h>
#define MAXSIZE 100
typedef struct node {
int x, y, dir;
} Node;
Node stack[MAXSIZE];
int top = -1;
void push(int x, int y, int dir) { // 入栈操作
top++;
stack[top].x = x;
stack[top].y = y;
stack[top].dir = dir;
}
Node pop() { // 出栈操作
top--;
return stack[top + 1];
}
int main() {
int maze[10][10] = { // 迷宫地图
{1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,1,0,0,0,0,1},
{1,0,1,0,1,0,1,1,0,1},
{1,0,1,0,1,0,0,0,0,1},
{1,0,1,1,1,1,1,1,0,1},
{1,0,0,0,0,0,0,0,0,1},
{1,0,1,0,1,1,1,1,0,1},
{1,0,1,0,0,0,0,0,0,1},
{1,0,0,0,1,1,1,1,0,1},
{1,1,1,1,1,1,1,1,1,1}
};
int visited[10][10] = {0}; // 记录是否访问过
int x = 1, y = 1, dir = 0; // dir表示当前方向(0表示向右,1表示向下,2表示向左,3表示向上)
int end_x = 8, end_y = 8; // 终点坐标
push(x, y, dir); // 将起点入栈
visited[x][y] = 1; // 标记起点已访问
while (top >= 0) { // 栈非空
Node cur = pop(); // 取出栈顶元素
x = cur.x;
y = cur.y;
dir = cur.dir;
while (dir < 4) { // 尝试四个方向
int next_x = x, next_y = y;
switch (dir) {
case 0: next_y++; break; // 向右
case 1: next_x++; break; // 向下
case 2: next_y--; break; // 向左
case 3: next_x--; break; // 向上
}
if (next_x == end_x && next_y == end_y) { // 到达终点
printf("(%d, %d)\n", x, y);
printf("(%d, %d)\n", end_x, end_y);
return 0;
}
if (maze[next_x][next_y] == 0 && visited[next_x][next_y] == 0) { // 可以走且未访问过
visited[next_x][next_y] = 1; // 标记已访问
push(x, y, dir); // 当前位置入栈
x = next_x; // 移动到下一个位置
y = next_y;
dir = 0; // 方向从右开始
} else {
dir++; // 尝试下一个方向
}
}
}
printf("No solution!\n");
return 0;
}
```
该代码利用栈来实现深度优先搜索,从起点开始遍历,每次尝试四个方向,如果可以走且未访问过,则将当前位置入栈,并移动到下一个位置。如果四个方向都不能走,则出栈回到上一个位置继续尝试。当到达终点时,输出路径并结束程序,否则输出“无解”。