#include <stdio.h>
#include <stdlib.h>

#define MAX_SIZE 100

typedef struct {
    int i;
    int j;
    int direction;
} Position;  // 定义位置结构体

typedef struct {
    Position data[MAX_SIZE];
    int top;
} Stack;  // 定义栈结构体

void initStack(Stack *s) {  // 初始化栈
    s->top = -1;
}

int isEmpty(Stack *s) {  // 判断栈是否为空
    return s->top == -1;
}

int isFull(Stack *s) {  // 判断栈是否已满
    return s->top == MAX_SIZE - 1;
}

void push(Stack *s, Position p) {  // 入栈
    if (isFull(s)) {
        printf("Stack overflow\n");
        return;
    }
    s->data[++s->top] = p;
}

Position pop(Stack *s) {  // 出栈
    if (isEmpty(s)) {
        printf("Stack underflow\n");
        Position p = {-1, -1, -1};
        return p;
    }
    return s->data[s->top--];
}

void solveMaze(int maze[][MAX_SIZE], int m, int n) {  // 解决迷宫问题
    Stack s;
    initStack(&s);  // 初始化栈

    Position entry = {0, 0, 0};  // 入口位置
    push(&s, entry);  // 将入口位置入栈

    while (!isEmpty(&s)) {  // 当栈不为空时
        Position current = pop(&s);  // 弹出栈顶位置
        int i = current.i;
        int j = current.j;
        int direction = current.direction;

        while (direction < 4) {  // 遍历四个方向
            int ni, nj;
            switch (direction) {
                case 0:  // 上
                    ni = i - 1;
                    nj = j;
                    break;
                case 1:  // 右
                    ni = i;
                    nj = j + 1;
                    break;
                case 2:  // 下
                    ni = i + 1;
                    nj = j;
                    break;
                case 3:  // 左
                    ni = i;
                    nj = j - 1;
                    break;
            }

            if (ni >= 0 && ni < m && nj >= 0 && nj < n && maze[ni][nj] == 0) {  // 如果下一个位置是可行走的
                maze[ni][nj] = 2;  // 标记为已访问
                Position next = {ni, nj, 0};  // 下一个位置
                push(&s, next);  // 入栈
                i = ni;
                j = nj;
                if (i == m - 1 && j == n - 1) {  // 如果到达出口位置
                    printf("(%d,%d,%d)\n", next.i + 1, next.j + 1, direction + 1);  // 输出路径
                    return;
                }
                direction = 0;  // 重新从上方向开始遍历
            } else {
                direction++;  // 尝试下一个方向
            }
        }
    }

    printf("No path found\n");  // 没有找到路径
}

int main() {
    int m, n;
    printf("Enter the size of the maze (m n): ");
    scanf("%d %d", &m, &n);

    int maze[MAX_SIZE][MAX_SIZE];
    printf("Enter the maze (0 for path, 1 for obstacle):\n");
    for (int i = 0; i < m; i++) {
        for (int j = 0; j < n; j++) {
            scanf("%d", &maze[i][j]);
        }
    }

    solveMaze(maze, m, n);  // 解决迷宫问题

    return 0;
}
C语言迷宫求解算法:深度优先搜索实现

原文地址: https://www.cveoy.top/t/topic/d42 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录