2024年3月4日发(作者:)
c语言走迷宫代码
以下是一个简单的 C 语言走迷宫代码示例,使用了递归算法:
```c
#include
#include
int main() {
int size, row, col, choice, i, j;
maze[0][0] = "*";
maze[1][0] = "O";
maze[0][1] = "O";
maze[1][1] = "*";
size = 2;
row = 2;
col = 2;
while (1) {
printf("Enter row: ");
scanf("%d", &row);
printf("Enter col: ");
scanf("%d", &col);
if (row < 0 || row > size || col < 0 || col > size) {
printf("Invalid row or col. Try again.
");
continue;
}
if (maze[row][col] != "*") {
printf("Current cell is free. Try again.
");
continue;
}
maze[row][col] = "X";
printf("Enter a choice (1-6): ");
scanf("%d", &choice);
switch (choice) {
case 1:
row++;
col = 0;
break;
case 2:
row--;
col = 0;
break;
case 3:
col++;
break;
case 4:
col--;
break;
case 5:
row--;
col = 1;
break;
case 6:
row++;
col = 1;
break;
default:
printf("Invalid choice. Try again.
");
continue;
}
}
printf(" maze: ");
for (i = 0; i < size * size; i++) {
for (j = 0; j < size; j++) {
if (maze[i][j] == "*")
printf("*");
else
printf("%c", maze[i][j]);
}
printf("
");
}
return 0;
}
```
该程序首先初始化了一个 2x2 的迷宫,其中 `maze[0][0]` 和
`maze[1][0]` 分别标记为 `"O"` 和 `"*"`,其他地方都为空。然后程序会要求用户输入行和列,然后根据输入更新迷宫。如果输入的行和列不合法,程序会提示并重新输入。如果输入的行和列合法,程序会更新迷宫,并让用户再次输入选择,以继续游戏。该程序使用了简单的递归算法,每次根据当前迷宫状态更新,如果当前状态无法更新,则递归到下一层。最终,程序会输出一个完整的迷宫,用户可以在其中探索。
发布者:admin,转转请注明出处:http://www.yc00.com/web/1709537733a1634933.html
评论列表(0条)