用c语言的栈实现迷宫代码
时间: 2024-04-29 15:25:46 浏览: 6
好的,我可以帮您回答这个问题。以下是C语言的栈实现迷宫代码的示例:
```
#include <stdio.h>
#define ROW 6
#define COL 6
int maze[ROW][COL] = {
{0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 0},
{0, 0, 1, 0, 0, 0},
{1, 0, 0, 1, 1, 0},
{0, 1, 0, 0, 1, 0},
{0, 0, 0, 1, 0, 0}
};
typedef struct point {
int x;
int y;
} Point;
Point stack[ROW * COL];
int top = -1;
void push(Point p)
{
stack[++top] = p;
}
Point pop()
{
return stack[top--];
}
int is_empty()
{
return top == -1;
}
int is_exit(Point p)
{
return p.x == ROW - 1 && p.y == COL - 1;
}
void print_path()
{
int i;
for (i = 0; i <= top; i++) {
printf("(%d, %d) ", stack[i].x, stack[i].y);
}
printf("\n");
}
int main()
{
Point start = {0, 0};
push(start);
while (!is_empty()) {
Point current = pop();
if (is_exit(current)) {
print_path();
return 0;
}
if (maze[current.x][current.y] == 0) {
continue;
}
maze[current.x][current.y] = 0;
if (current.y < COL - 1) {
Point right = {current.x, current.y + 1};
push(right);
}
if (current.x < ROW - 1) {
Point down = {current.x + 1, current.y};
push(down);
}
if (current.y > 0) {
Point left = {current.x, current.y - 1};
push(left);
}
if (current.x > 0) {
Point up = {current.x - 1, current.y};
push(up);
}
}
printf("No path found.\n");
return 0;
}
```
希望我的回答对您有帮助!