给定一个M×N的迷宫图、入口与出口、行走规则。求一条从指定入口到 出口的路径。所求路径必须是简单路径,即路径不重复。使用栈的结构完成。要求用c语言
时间: 2024-03-19 15:45:25 浏览: 30
以下是使用DFS算法和栈结构求解迷宫问题的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX_MAZE_SIZE 100
typedef struct
{
int x;
int y;
} Point;
typedef struct
{
Point data[MAX_MAZE_SIZE];
int top;
} Stack;
void init(Stack *stack)
{
stack->top = -1;
}
bool isEmpty(Stack *stack)
{
return stack->top == -1;
}
bool isFull(Stack *stack)
{
return stack->top == MAX_MAZE_SIZE - 1;
}
bool push(Stack *stack, Point p)
{
if (isFull(stack))
{
return false;
}
stack->data[++stack->top] = p;
return true;
}
bool pop(Stack *stack, Point *p)
{
if (isEmpty(stack))
{
return false;
}
*p = stack->data[stack->top--];
return true;
}
bool peek(Stack *stack, Point *p)
{
if (isEmpty(stack))
{
return false;
}
*p = stack->data[stack->top];
return true;
}
void printPath(Point path[], int size)
{
for (int i = 0; i < size; i++)
{
printf("(%d, %d) ", path[i].x, path[i].y);
}
printf("\n");
}
bool dfs(int maze[][MAX_MAZE_SIZE], int m, int n, Point start, Point end, Stack *path)
{
if (start.x < 0 || start.x >= m || start.y < 0 || start.y >= n)
{
return false;
}
if (maze[start.x][start.y] != 0)
{
return false;
}
maze[start.x][start.y] = 1;
push(path, start);
if (start.x == end.x && start.y == end.y)
{
return true;
}
Point next = {start.x, start.y + 1};
if (dfs(maze, m, n, next, end, path))
{
return true;
}
next.x = start.x + 1;
next.y = start.y;
if (dfs(maze, m, n, next, end, path))
{
return true;
}
next.x = start.x;
next.y = start.y - 1;
if (dfs(maze, m, n, next, end, path))
{
return true;
}
next.x = start.x - 1;
next.y = start.y;
if (dfs(maze, m, n, next, end, path))
{
return true;
}
pop(path, &next);
return false;
}
int main()
{
int maze[MAX_MAZE_SIZE][MAX_MAZE_SIZE] = {
{0, 0, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 1, 0, 0, 0},
{0, 1, 1, 1, 0},
{0, 0, 0, 0, 0},
};
int m = 5, n = 5;
Point start = {1, 1};
Point end = {3, 3};
Stack path;
init(&path);
if (dfs(maze, m, n, start, end, &path))
{
Point p;
int size = 0;
Point pathArray[MAX_MAZE_SIZE];
while (pop(&path, &p))
{
pathArray[size++] = p;
}
printf("Path found: ");
printPath(pathArray, size);
}
else
{
printf("Path not found!\n");
}
return 0;
}
```
其中,dfs函数使用深度优先搜索算法来遍历迷宫,每次遍历时先检查当前节点是否在迷宫范围内、是否为障碍物,然后将其标记为已访问,并将其入栈。如果当前节点是终点,则返回true表示找到了一条路径;否则,依次遍历当前节点的四个邻居节点。如果找到了一条路径,则通过pop函数依次将路径上的节点出栈,存储到pathArray数组中,并通过printPath函数打印路径。如果遍历完所有节点仍未找到路径,则返回false。