我正在尝试编写一个生成二维迷宫的程序。迷宫的主体是一个 2-d int 数组。边界单元格的值为 2。阻塞单元格(墙)的值为 1,空单元格(路径)的值为 0。最初,我将所有单元格的值设置为 1。然后,从在顶行的随机列中,我在迷宫中移动,将当前单元格设置为 0,直到到达底行。
这一切都很好,除了,而不是单行路径,我经常以大范围的 0 结束。因此,我尝试添加到 if 语句以防止它在其周围的单元格已经为零时将单元格标记为零。不幸的是,我的逻辑存在一些缺陷,导致程序在我运行时永远运行而没有打印任何内容。请帮我找出那个缺陷。
我对编程相当陌生,并且将其作为学习练习,因此我也对其他算法建议持开放态度。谢谢
我的代码:
package RoboProj;
import java.util.Random;
public class Maze {
public int[][] grid;
final int width, height;
public Maze() {
width = 20;
height = 20;
grid = new int[width][height];
makeMaze();
}
public void makeMaze() {
//* empty = 0, wall = 1, border = 2, travelled =3;
//mark borders
for (int curr = 0; curr < height; curr++) {
grid[0][curr] = 2; //top
grid[curr][0]=2; //left
grid[height -1][curr] = 2; //bottom
grid[curr][width-1] = 2; //right
}
//initially mark all cells as walls
for (int row = 1; row < height-1; row++){
for (int col = 1; col < width-1; col++){
grid[row][col]=1;
}
}
int row = 0;
Random r = new Random();
int col = r.nextInt(width);
grid[row][col] = 0;
while (row != height-1){
int next = r.nextInt(4);
if (next == 0 && row-1 > 0 && grid[row-1][col-1] == 1 && grid[row-1][col+1] == 1){
grid[row-1][col]=0;
row = row-1;
// System.out.print(next);
}
if (next == 1 && grid[row+1][col-1] == 1 && grid[row+1][col+1] == 1){
grid[row+1][col]=0;
row = row+1;
// System.out.print(next);
}
if (next == 2&& col-1 > 0 && grid[row+1][col-1] == 1 && grid[row-1][col-1] == 1){
grid[row][col-1]=0;
col = col-1;
// System.out.print(next);
}
if (next == 3 && col+1 < width-1 && grid[row-1][col+1] == 1 && grid[row+1][col+1] == 1){
grid[row][col+1]=0;
col = col+1;
// System.out.print(next);
}
}
}
}
@Anupam Saini:我正在寻找这样的东西,其中“途径”的宽度永远不会超过一个单元格。
1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 0 1 1 1 1 1 1 1 1 1 1 1 1 1
1 1 1 1 1 1 0 0 0 0 0 0 0 0 0 0 1 1 1 1
1 1 1 1 1 1 1 1 1 1 1 1 1 1 1 0 1 1 1 1