迷宫问题求解

迷官问题是实验心理学的一个经典问题,心理学家把一只老鼠从一个无顶盖的大盒子的入口处赶进迷宫,迷宫中设置很多隔壁,对前进方向形成了多处障碍,心理学家在迷宫的唯一出口处放置了一块奶酪,吸引老鼠在迷宫中寻找通路到达出口。设计回溯算法实现迷宫求解。

 解题思路:

设置数组保存八个移动方向

主函数

①输入迷宫大小

③输入迷宫布局(障碍和通路)

④调用solveMaze,若找到解则输出路径,否则输出No solution found.

solveMaze函数

①检查是否越界或者遇到墙壁,若是,则返回0,否则②

③标记当前位置为已访问

④如果已经找到出口,则返回1,否则⑤

⑤尝试八个方向的移动,尝试成功则返回1,否则⑥

⑥如果所有方向都失败,标记当前位置为未访问,返回0

流程图:

源代码:

#include <stdio.h>
#define MAX_SIZE 20

int maze[MAX_SIZE][MAX_SIZE];
int solution[MAX_SIZE][MAX_SIZE];
int rows, cols;

int dx[] = {-1, -1, 0, 1, 1, 1, 0, -1};
int dy[] = {0, 1, 1, 1, 0, -1, -1, -1};

int solveMaze(int x, int y);

int main() {
    printf("Enter the number of rows and columns (max %d): ", MAX_SIZE);
    scanf("%d %d", &rows, &cols);
    printf("Enter the maze layout (1 for wall, 0 for path, S for start, E for exit):\n");
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            scanf("%d", &maze[i][j]);
            solution[i][j] = 0;
        }
    }
    if (solveMaze(0, 0)) {
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                printf("%d ", solution[i][j]);
            }
            printf("\n");
        }
    } else {
        printf("No solution found.\n");
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                printf("%d ", solution[i][j]);
            }
            printf("\n");
        }
    }
    return 0;
}

int solveMaze(int x, int y) {
    if (x < 0 || x >= rows || y < 0 || y >= cols || maze[x][y] == 1) {
        return 0;
    }
    solution[x][y] = 1;
    if (x == rows-1 && y == cols-1) {
        return 1;
    }
    for (int i = 0; i < 8; i++) {
        if (solveMaze(x + dx[i], y + dy[i])) {
            return 1;
        }
    }
    solution[x][y] = 0;
    return 0;
}
  • 6
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值