用c语言数据结构写一个迷宫求解
时间: 2023-10-08 07:14:27 浏览: 52
好的,下面是一个使用C语言数据结构(栈)来解决迷宫问题的示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
#define ROW 8
#define COL 8
#define MAX_STACK_SIZE 100
typedef struct {
int x;
int y;
} Point;
typedef struct {
Point data[MAX_STACK_SIZE];
int top;
} Stack;
void push(Stack *s, Point p) {
if (s->top < MAX_STACK_SIZE) {
s->data[++s->top] = p;
}
}
Point pop(Stack *s) {
if (s->top > 0) {
return s->data[s->top--];
} else {
Point p = {-1, -1};
return p;
}
}
int is_empty(Stack *s) {
return s->top == 0;
}
void print_maze(int maze[ROW][COL]) {
printf("Maze:\n");
for (int i = 0; i < ROW; i++) {
for (int j = 0; j < COL; j++) {
printf("%d ", maze[i][j]);
}
printf("\n");
}
}
int solve_maze(int maze[ROW][COL], Point start, Point end) {
Stack s;
s.top = 0;
push(&s, start);
maze[start.x][start.y] = -1;
while (!is_empty(&s)) {
Point current = pop(&s);
if (current.x == end.x && current.y == end.y) {
printf("\nSolution found!\n");
print_maze(maze);
return 1;
}
if (current.x > 0 && maze[current.x-1][current.y] == 0) {
push(&s, (Point){current.x-1, current.y});
maze[current.x-1][current.y] = maze[current.x][current.y] - 1;
}
if (current.y > 0 && maze[current.x][current.y-1] == 0) {
push(&s, (Point){current.x, current.y-1});
maze[current.x][current.y-1] = maze[current.x][current.y] - 1;
}
if (current.x < ROW-1 && maze[current.x+1][current.y] == 0) {
push(&s, (Point){current.x+1, current.y});
maze[current.x+1][current.y] = maze[current.x][current.y] - 1;
}
if (current.y < COL-1 && maze[current.x][current.y+1] == 0) {
push(&s, (Point){current.x, current.y+1});
maze[current.x][current.y+1] = maze[current.x][current.y] - 1;
}
}
printf("\nSolution not found.\n");
return 0;
}
int main() {
int maze[ROW][COL] = {
{0, 0, 0, 0, 0, 0, 0, 0},
{0, 1, 1, 0, 1, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
{0, 1, 0, 0, 1, 1, 0, 1},
{0, 1, 1, 1, 0, 0, 1, 0},
{0, 1, 0, 0, 0, 1, 1, 0},
{0, 0, 0, 1, 0, 0, 0, 0},
{0, 1, 1, 1, 0, 1, 1, 0}
};
Point start = {1, 1};
Point end = {6, 6};
solve_maze(maze, start, end);
return 0;
}
```
这个代码使用了一个栈来保存迷宫中的位置,并且在搜索过程中使用了广度优先搜索的方式。你可以根据自己的需要修改这个代码,例如更改迷宫的大小、起点和终点的位置等。