用C语言解决迷宫问题,迷宫大小由输入决定
时间: 2023-07-31 17:05:28 浏览: 121
以下是一个用C语言解决迷宫问题的示例代码,迷宫大小通过用户输入确定,其中0代表通路,1代表障碍物:
```
#include <stdio.h>
#include <stdlib.h>
#define MAX 100
int maze[MAX][MAX];
int solution[MAX][MAX];
int rows, cols;
void printMaze() {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", maze[i][j]);
}
printf("\n");
}
}
int solve(int x, int y) {
if (x == rows - 1 && y == cols - 1) {
solution[x][y] = 1;
return 1;
}
if (x >= 0 && x < rows && y >= 0 && y < cols && maze[x][y] == 0 && solution[x][y] == 0) {
solution[x][y] = 1;
if (solve(x + 1, y)) {
return 1;
}
if (solve(x, y + 1)) {
return 1;
}
if (solve(x - 1, y)) {
return 1;
}
if (solve(x, y - 1)) {
return 1;
}
solution[x][y] = 0;
return 0;
}
return 0;
}
int main() {
printf("Enter number of rows: ");
scanf("%d", &rows);
printf("Enter number of columns: ");
scanf("%d", &cols);
printf("Enter maze:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
scanf("%d", &maze[i][j]);
}
}
printf("Maze:\n");
printMaze();
if (solve(0, 0)) {
printf("\nSolution:\n");
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%d ", solution[i][j]);
}
printf("\n");
}
} else {
printf("\nNo solution.\n");
}
return 0;
}
```
该代码使用递归的方式解决迷宫问题,并且在解决过程中记录并输出解决方案。
阅读全文