利用c语言做迷宫
时间: 2023-08-25 08:06:03 浏览: 49
好的,下面是一个简单的迷宫生成和解决的 C 代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
int maze[ROWS][COLS];
int visited[ROWS][COLS];
void initMaze() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (i == 0 || i == ROWS - 1 || j == 0 || j == COLS - 1)
maze[i][j] = 1;
else
maze[i][j] = 0;
visited[i][j] = 0;
}
}
}
void printMaze() {
for (int i = 0; i < ROWS; i++) {
for (int j = 0; j < COLS; j++) {
if (maze[i][j] == 1)
printf("# ");
else
printf(" ");
}
printf("\n");
}
}
void generateMaze() {
srand(time(NULL));
int row = rand() % (ROWS - 2) + 1;
int col = rand() % (COLS - 2) + 1;
maze[row][col] = 1;
visited[row][col] = 1;
int directions[4][2] = {{-1, 0}, {1, 0}, {0, -1}, {0, 1}};
int count = 0;
while (count < ROWS * COLS - 1) {
int dir = rand() % 4;
int nextRow = row + directions[dir][0];
int nextCol = col + directions[dir][1];
if (nextRow >= 0 && nextRow < ROWS && nextCol >= 0 && nextCol < COLS && visited[nextRow][nextCol] == 0) {
int wallRow = row + directions[dir][0] / 2;
int wallCol = col + directions[dir][1] / 2;
maze[wallRow][wallCol] = 1;
row = nextRow;
col = nextCol;
visited[row][col] = 1;
count++;
}
}
}
typedef struct {
int row;
int col;
int dir;
} Node;
Node stack[ROWS * COLS];
int top = -1;
void push(Node node) {
stack[++top] = node;
}
Node pop() {
return stack[top--];
}
int isStackEmpty() {
return top == -1;
}
void solveMaze(int startRow, int startCol, int endRow, int endCol) {
push((Node){startRow, startCol, -1});
while (!isStackEmpty()) {
Node node = pop();
int row = node.row;
int col = node.col;
int dir = node.dir + 1;
while (dir < 4) {
int nextRow = row + directions[dir][0];
int nextCol = col + directions[dir][1];
if (nextRow == endRow && nextCol == endCol) {
printf("(%d, %d) ", row, col);
printf("(%d, %d)\n", nextRow, nextCol);
return;
}
if (nextRow >= 0 && nextRow < ROWS && nextCol >= 0 && nextCol < COLS && maze[nextRow][nextCol] == 0 && visited[nextRow][nextCol] == 0) {
visited[nextRow][nextCol] = 1;
push((Node){row, col, dir});
row = nextRow;
col = nextCol;
dir = -1;
}
dir++;
}
}
printf("No solution found!\n");
}
int main() {
initMaze();
generateMaze();
printMaze();
solveMaze(1, 1, ROWS - 2, COLS - 2);
return 0;
}
```
这个代码会生成一个 $10 \times 10$ 的迷宫,然后随机选择一个起点和终点,并且通过栈回溯算法求解迷宫。你可以根据需要调整迷宫大小和起点、终点坐标。