c语言先建造一个迷宫 “u”表示向上走“d”表示向下走 “l”表示向左走“人”表示向右走 做后用“u”“d”“l”“r”表示出路径
时间: 2023-07-24 13:12:13 浏览: 40
以下是一个简单的迷宫生成程序,可以用来生成迷宫并输出路径:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
#define WALL '#'
#define PATH ' '
#define START 'S'
#define END 'E'
#define PLAYER 'P'
#define UP 'u'
#define DOWN 'd'
#define LEFT 'l'
#define RIGHT 'r'
char maze[ROWS][COLS];
void generateMaze();
void printMaze();
int solveMaze(int row, int col, char direction);
int main() {
srand(time(NULL));
generateMaze();
printf("Maze:\n");
printMaze();
printf("Path:\n");
solveMaze(0, 0, RIGHT);
return 0;
}
void generateMaze() {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
if (i == 0 || i == ROWS - 1 || j == 0 || j == COLS - 1) {
maze[i][j] = WALL;
} else {
maze[i][j] = PATH;
}
}
}
maze[0][0] = START;
maze[ROWS - 1][COLS - 1] = END;
int row = rand() % (ROWS - 2) + 1;
int col = rand() % (COLS - 2) + 1;
maze[row][col] = PLAYER;
}
void printMaze() {
int i, j;
for (i = 0; i < ROWS; i++) {
for (j = 0; j < COLS; j++) {
printf("%c ", maze[i][j]);
}
printf("\n");
}
}
int solveMaze(int row, int col, char direction) {
if (maze[row][col] == END) {
return 1;
}
if (maze[row][col] == WALL || maze[row][col] == PLAYER) {
return 0;
}
maze[row][col] = PLAYER;
if (direction != UP && solveMaze(row + 1, col, DOWN)) {
printf("%c ", DOWN);
return 1;
}
if (direction != DOWN && solveMaze(row - 1, col, UP)) {
printf("%c ", UP);
return 1;
}
if (direction != LEFT && solveMaze(row, col + 1, RIGHT)) {
printf("%c ", RIGHT);
return 1;
}
if (direction != RIGHT && solveMaze(row, col - 1, LEFT)) {
printf("%c ", LEFT);
return 1;
}
return 0;
}
```
程序中使用了递归来解决迷宫问题。首先生成一个随机的迷宫,然后从起点开始,尝试向不同的方向走,如果能够找到一条通路,就输出对应的方向并返回1,否则返回0。在递归回溯的过程中,如果遇到墙壁或者已经走过的路,就返回0。