自动生成迷宫java
时间: 2024-06-18 18:02:00 浏览: 197
自动生成迷宫是一个经典的计算机科学问题,可以使用多种算法来解决,其中最常见的是深度优先搜索(DFS)或宽度优先搜索(BFS)。在Java中,我们可以创建一个二维数组来表示迷宫,然后用这些算法来填充或标记路径。
以下是一个简单的DFS生成迷宫的Java代码示例:
```java
import java.util.*;
public class MazeGenerator {
private static final char WALL = '#', PATH = ' ';
private int[][] maze; // 二维数组,WALL表示墙,PATH表示通道
public MazeGenerator(int width, int height) {
maze = new int[height][width];
for (int i = 0; i < height; i++) {
Arrays.fill(maze[i], WALL);
}
}
public void generateMaze(int startX, int startY) {
stack(startX, startY);
maze[startY][startX] = PATH;
}
private Stack<int[]> stack(int x, int y) {
Stack<int[]> stack = new Stack<>();
stack.push(new int[]{x, y});
while (!stack.isEmpty()) {
int[] current = stack.pop();
if (isValid(current - 1, current)) {
maze[current][current[0] - 1] = PATH;
stack.push(new int[]{current - 1, current});
}
if (isValid(current + 1, current)) {
maze[current][current + 1] = PATH;
stack.push(new int[]{current[0] + 1, current});
}
if (isValid(current, current - 1)) {
maze[current - 1][current[0]] = PATH;
stack.push(new int[]{current, current - 1});
}
if (isValid(current[0], current + 1)) {
maze[current + 1][current] = PATH;
stack.push(new int[]{current, current + 1});
}
}
}
private boolean isValid(int x, int y) {
return x >= 0 && x < maze.length && y >= 0 && y < maze.length && maze[y][x] == WALL;
}
// 添加其他方法来获取和打印迷宫
// ...
}
```
阅读全文