java生成迷宫算法
时间: 2023-07-10 08:22:11 浏览: 82
生成迷宫的算法有很多种,其中比较常见的是深度优先搜索(DFS)和广度优先搜索(BFS)。
下面是使用DFS算法生成迷宫的Java代码示例:
```java
import java.util.*;
public class MazeGenerator {
private int width;
private int height;
private int[][] maze;
private boolean[][] visited;
public MazeGenerator(int width, int height) {
this.width = width;
this.height = height;
this.maze = new int[2 * width + 1][2 * height + 1];
this.visited = new boolean[width][height];
}
public void generate() {
// 初始化迷宫,所有格子都是墙壁
for (int i = 0; i < 2 * width + 1; i++) {
for (int j = 0; j < 2 * height + 1; j++) {
maze[i][j] = 1;
}
}
// 从起点开始生成迷宫
dfs(0, 0);
// 将迷宫的外围设置为墙壁
for (int i = 0; i < 2 * width + 1; i++) {
maze[i][0] = maze[i][2 * height] = 1;
}
for (int i = 0; i < 2 * height + 1; i++) {
maze[0][i] = maze[2 * width][i] = 1;
}
}
public int[][] getMaze() {
return maze;
}
private void dfs(int x, int y) {
visited[x][y] = true;
// 随机打乱四个方向的顺序
List<Integer> directions = Arrays.asList(0, 1, 2, 3);
Collections.shuffle(directions);
for (int direction : directions) {
int dx = 0, dy = 0;
switch (direction) {
case 0: // 上
if (y == 0 || visited[x][y - 1]) {
continue;
}
dy = -1;
break;
case 1: // 右
if (x == width - 1 || visited[x + 1][y]) {
continue;
}
dx = 1;
break;
case 2: // 下
if (y == height - 1 || visited[x][y + 1]) {
continue;
}
dy = 1;
break;
case 3: // 左
if (x == 0 || visited[x - 1][y]) {
continue;
}
dx = -1;
break;
}
// 将当前格子和相邻格子之间的墙壁打通
maze[2 * x + 1 + dx][2 * y + 1 + dy] = 0;
dfs(x + dx, y + dy);
}
}
}
```
使用方法:
```java
MazeGenerator generator = new MazeGenerator(10, 10);
generator.generate();
int[][] maze = generator.getMaze();
```
其中,`width`和`height`表示迷宫的宽度和高度,`maze`是一个二维数组,表示生成的迷宫,其中`0`表示通路,`1`表示墙壁。