数据结构--利用栈解决迷宫问题

目录

一 简介

二 代码实现


一 简介

迷宫问题通常可以用深度优先搜索(DFS)或者广度优先搜索(BFS)算法解决,这两种算法都可以结合栈来实现。

二 代码实现

下面以深度优先搜索为例,演示如何使用C语言和栈来解决迷宫问题。

首先,我们需要定义迷宫和路径的状态,假设迷宫用二维数组表示,其中0代表通路,1代表墙壁。然后我们从起始点开始,每次尝试向四个方向移动(上、下、左、右),如果能移动则继续深入探索,不能移动则回退到上一个位置,直到找到出口或所有路径都被探索过。

#define WALL 1
#define PATH 0
#define VISITED 2

// 迷宫结构体定义
typedef struct {
    int rows, cols;
    int maze[10][10]; // 假设迷宫最大10x10,实际情况应根据具体迷宫大小调整
} Maze;

// 起点和终点坐标
typedef struct {
    int row, col;
} Point;

// 使用栈保存路径
typedef struct Node {
    Point pos;
    struct Node *next;
} StackNode;

// 初始化栈
void InitStack(StackNode **top) {
    *top = NULL;
}

// 入栈
void Push(StackNode **top, Point pos) {
    StackNode *newNode = (StackNode*)malloc(sizeof(StackNode));
    newNode->pos = pos;
    newNode->next = *top;
    *top = newNode;
}

// 出栈
Point Pop(StackNode **top) {
    StackNode *temp = *top;
    Point pos = temp->pos;
    *top = temp->next;
    free(temp);
    return pos;
}

// 判断栈是否为空
int IsEmpty(StackNode *top) {
    return top == NULL;
}

// 判断当前位置是否越界或为墙
int IsValid(Maze *maze, Point pos) {
    return pos.row >= 0 && pos.row < maze->rows && 
           pos.col >= 0 && pos.col < maze->cols && 
           maze->maze[pos.row][pos.col] != WALL;
}

// DFS求解迷宫
int SolveMaze(Maze *maze, Point start, Point end) {
    maze->maze[start.row][start.col] = VISITED; // 标记起点已访问
    StackNode *stackTop = NULL;
    Push(&stackTop, start);

    while (!IsEmpty(stackTop)) {
        Point current = Pop(&stackTop);
        
        // 如果到达终点,则返回成功
        if (current.row == end.row && current.col == end.col) {
            return SUCCESS;
        }

        // 尝试向四个方向移动
        for (int dir = 0; dir < 4; ++dir) {
            int newRow = current.row + directions[dir][0];
            int newCol = current.col + directions[dir][1];

            if (IsValid(maze, (Point){newRow, newCol})) {
                maze->maze[newRow][newCol] = VISITED; // 标记已访问
                Push(&stackTop, (Point){newRow, newCol}); // 把新位置压入栈
            }
        }
    }

    return FAILURE; // 所有路径都探索过了,但是没找到出口
}

// 方向数组,分别对应上(-1, 0)、下(1, 0)、左(0, -1)、右(0, 1)
int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

以上代码只是一个基础的框架,实际使用时需要填充具体的迷宫信息,并在解决问题后恢复迷宫原始状态。此外,对于更大的迷宫,建议使用递归的方式来实现DFS,这样代码会更加简洁易读。

  • 22
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 12
    评论
以下是使用栈求解迷宫问题的所有路径及最短路径的C语言程序: ```c #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #define ROW 5 // 迷宫行数 #define COL 5 // 迷宫列数 struct Point { int x; // 横坐标 int y; // 纵坐标 }; struct Stack { struct Point data[ROW * COL]; // 数据 int top; // 顶指针 }; // 初始化 void initStack(struct Stack *s) { s->top = -1; } // 判断是否为空 bool isEmpty(struct Stack *s) { return s->top == -1; } // 判断是否已满 bool isFull(struct Stack *s) { return s->top == ROW * COL - 1; } // 入 void push(struct Stack *s, struct Point p) { if (isFull(s)) { printf("Stack is full!\n"); return; } s->top++; s->data[s->top] = p; } // 出 struct Point pop(struct Stack *s) { if (isEmpty(s)) { printf("Stack is empty!\n"); exit(-1); } struct Point p = s->data[s->top]; s->top--; return p; } // 判断当前位置是否合法 bool isValid(int maze[][COL], int x, int y) { if (x < 0 || x >= ROW || y < 0 || y >= COL || maze[x][y] == 1) { return false; } return true; } // 求解所有路径 void findAllPaths(int maze[][COL], int startX, int startY, int endX, int endY) { struct Stack s; initStack(&s); struct Point start = {startX, startY}; push(&s, start); while (!isEmpty(&s)) { struct Point cur = pop(&s); if (cur.x == endX && cur.y == endY) { // 到达终点,输出路径 for (int i = 0; i <= s.top; i++) { printf("(%d, %d) ", s.data[i].x, s.data[i].y); } printf("(%d, %d)\n", endX, endY); } else { // 继续搜索 maze[cur.x][cur.y] = 1; // 标记已经走过 if (isValid(maze, cur.x - 1, cur.y)) { // 上 struct Point next = {cur.x - 1, cur.y}; push(&s, next); } if (isValid(maze, cur.x, cur.y + 1)) { // 右 struct Point next = {cur.x, cur.y + 1}; push(&s, next); } if (isValid(maze, cur.x + 1, cur.y)) { // 下 struct Point next = {cur.x + 1, cur.y}; push(&s, next); } if (isValid(maze, cur.x, cur.y - 1)) { // 左 struct Point next = {cur.x, cur.y - 1}; push(&s, next); } maze[cur.x][cur.y] = 0; // 恢复标记 } } } // 求解最短路径 void findShortestPath(int maze[][COL], int startX, int startY, int endX, int endY) { struct Stack s1, s2; initStack(&s1); initStack(&s2); struct Point start = {startX, startY}; push(&s1, start); while (!isEmpty(&s1)) { struct Point cur = pop(&s1); if (cur.x == endX && cur.y == endY) { // 到达终点,输出路径 push(&s2, cur); for (int i = 0; !isEmpty(&s1); i++) { push(&s2, cur); cur = pop(&s1); } push(&s2, cur); while (!isEmpty(&s2)) { struct Point p = pop(&s2); printf("(%d, %d) ", p.x, p.y); } printf("\n"); return; } else { // 继续搜索 maze[cur.x][cur.y] = 1; // 标记已经走过 if (isValid(maze, cur.x - 1, cur.y)) { // 上 struct Point next = {cur.x - 1, cur.y}; push(&s1, next); } if (isValid(maze, cur.x, cur.y + 1)) { // 右 struct Point next = {cur.x, cur.y + 1}; push(&s1, next); } if (isValid(maze, cur.x + 1, cur.y)) { // 下 struct Point next = {cur.x + 1, cur.y}; push(&s1, next); } if (isValid(maze, cur.x, cur.y - 1)) { // 左 struct Point next = {cur.x, cur.y - 1}; push(&s1, next); } maze[cur.x][cur.y] = 0; // 恢复标记 } } } int main() { int maze[ROW][COL] = { // 迷宫地图,1表示障碍,0表示可以通过 {0, 1, 0, 0, 0}, {0, 1, 0, 1, 0}, {0, 0, 0, 0, 0}, {1, 1, 1, 0, 0}, {0, 0, 0, 0, 1} }; printf("All paths:\n"); findAllPaths(maze, 0, 0, 4, 4); printf("Shortest path:\n"); findShortestPath(maze, 0, 0, 4, 4); return 0; } ``` 上述程序中,我们使用了一个结构体`Point`来表示迷宫中的坐标,使用一个结构体`Stack`来表示。`findAllPaths`函数用来求解所有路径,`findShortestPath`函数用来求解最短路径。在搜索过程中,我们使用一个二维数组`maze`来标记哪些位置已经走过,避免重复搜索。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值