迷官问题是实验心理学的一个经典问题,心理学家把一只老鼠从一个无顶盖的大盒子的入口处赶进迷宫,迷宫中设置很多隔壁,对前进方向形成了多处障碍,心理学家在迷宫的唯一出口处放置了一块奶酪,吸引老鼠在迷宫中寻找通路到达出口。设计回溯算法实现迷宫求解。
解题思路:
设置数组保存八个移动方向
主函数
①输入迷宫大小
③输入迷宫布局(障碍和通路)
④调用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;
}