上面的迷宫由用户生成,请重新编写一份C语言程序
时间: 2024-04-30 09:20:38 浏览: 14
以下是一份基于用户输入的迷宫生成程序:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define ROWS 10
#define COLS 10
void printMaze(int maze[][COLS], int rows, int cols) {
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
printf("%c ", maze[i][j] ? '#' : ' ');
}
printf("\n");
}
}
int validateInput(int input, int min, int max) {
if (input < min || input > max) {
printf("Invalid input! Please enter a number between %d and %d: ", min, max);
return 0;
}
return 1;
}
int main() {
srand(time(NULL));
int maze[ROWS][COLS] = {0};
int startRow, startCol, endRow, endCol;
// Prompt user for start and end positions
do {
printf("Enter the starting row and column (separated by a space): ");
scanf("%d %d", &startRow, &startCol);
} while (!validateInput(startRow, 0, ROWS-1) || !validateInput(startCol, 0, COLS-1));
do {
printf("Enter the ending row and column (separated by a space): ");
scanf("%d %d", &endRow, &endCol);
} while (!validateInput(endRow, 0, ROWS-1) || !validateInput(endCol, 0, COLS-1));
// Generate maze
maze[startRow][startCol] = 1; // Starting point
maze[endRow][endCol] = 1; // Ending point
int currentRow = startRow, currentCol = startCol;
while (currentRow != endRow || currentCol != endCol) {
// Generate random direction
int direction = rand() % 4;
switch (direction) {
case 0: // Up
if (currentRow > 0 && !maze[currentRow-1][currentCol]) {
maze[currentRow-1][currentCol] = 1;
currentRow--;
}
break;
case 1: // Right
if (currentCol < COLS-1 && !maze[currentRow][currentCol+1]) {
maze[currentRow][currentCol+1] = 1;
currentCol++;
}
break;
case 2: // Down
if (currentRow < ROWS-1 && !maze[currentRow+1][currentCol]) {
maze[currentRow+1][currentCol] = 1;
currentRow++;
}
break;
case 3: // Left
if (currentCol > 0 && !maze[currentRow][currentCol-1]) {
maze[currentRow][currentCol-1] = 1;
currentCol--;
}
break;
}
}
// Print maze
printMaze(maze, ROWS, COLS);
return 0;
}
```
这份程序通过 `validateInput` 函数来验证用户输入的起点和终点位置是否合法,并通过 `printMaze` 函数来打印迷宫。在生成迷宫时,程序会随机生成一个方向,检查该方向是否可以生成新的迷宫路径,如果可以则生成该路径并移动当前位置,直到当前位置到达终点。