我正在尝试实现Prim maze生成算法:
删除一些实现细节我的实现如下:
Cell[][] maze
是带有单元格的矩阵。每个单元格都有左/右/上/按钮墙。边界墙标记为boolean frontier
并且不是实施的一部分,因为我想保持迷宫框架。
public Cell[][] prim(){
List<Wall> walls = new ArrayList<Wall>();
//Pick a cell, mark it as part of the maze
int initialCellI = rnd(sizeX)-1;
int initialCellJ = rnd(sizeY)-1;
Cell randomCell = maze[initialCellI][initialCellJ];
randomCell.setPartOftheMaze(true);
//Add the walls of the cell to the wall list.
if ((randomCell.getLeft() != null) && (!randomCell.getLeft().isFrontier()))
walls.add(randomCell.getLeft());
if ((randomCell.getRight() != null) && (!randomCell.getRight().isFrontier()))
walls.add(randomCell.getRight());
if ((randomCell.getButtom() != null) && (!randomCell.getButtom().isFrontier()))
walls.add(randomCell.getButtom());
if ((randomCell.getUp() != null) && (!randomCell.getUp().isFrontier()))
walls.add(randomCell.getUp());
//While there are walls in the list:
while (!walls.isEmpty()){
//Pick a random wall from the list.
Wall randomWall = randomElement(walls);
//pick the cell opposite to this wall.
Cell opositeSideCell = getNeightbourCell(randomWall, maze);
if (opositeSideCell.isPartOftheMaze()){
//If the cell on the opposite side already was in the maze, remove the wall from the list.
walls.remove(randomWall);
}
else{
// Make the wall a passage and mark the cell on the opposite side as part of the maze.
this.removeWall(randomWall, maze);
opositeSideCell.setPartOftheMaze(true);
//Add the walls of the cell to the wall list.
if ((opositeSideCell.getLeft() != null) && (!opositeSideCell.getLeft().isFrontier()))
walls.add(opositeSideCell.getLeft());
if ((opositeSideCell.getRight() != null) && (!opositeSideCell.getRight().isFrontier()))
walls.add(opositeSideCell.getRight());
if ((opositeSideCell.getButtom() != null) && (!opositeSideCell.getButtom().isFrontier()))
walls.add(opositeSideCell.getButtom());
if ((opositeSideCell.getUp() != null) && (!opositeSideCell.getUp().isFrontier()))
walls.add(opositeSideCell.getUp());
}
}
return maze;
}
我的问题是我的迷宫没有完成,并且没有遍历所有细胞。 有时只有几个细胞遍历,几乎所有细胞都已完成。我相信我错过了什么bur无法弄清楚是什么。
请帮忙。
请参阅下面的部分遍历迷宫图片。
答案 0 :(得分:1)
好吧,我解决了这个问题。 这个纯Java问题与算法无关。我比较了两面墙。
public class Wall{
Point p1;
Point p2;
}
public class Point{
int x;
int y;
}
如果我使用p1和p2实现Wall类equals()和hashCode()。然后在 leftCell.rightWall将等于rightCell.leftWall,这就是问题所在。