gpt4 book ai didi

java - 迷宫生成prim算法并不是所有的单元格都被遍历

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:12:54 26 4
gpt4 key购买 nike

我正在尝试实现 Prim 迷宫生成算法:

  • 从布满墙壁的网格开始。
  • 选择一个单元格,将其标记为迷宫的一部分。添加单元格的壁到墙上列表。
  • 虽然列表中有墙:
    • 从列表中随机选择一堵墙。如果对面的cell
      尚未进入迷宫:
      • 把墙做成 channel 并将对面的单元格标记为迷宫的一部分。
      • 将单元格的相邻墙壁添加到墙壁列表中。
    • 如果对面的单元格已经在迷宫中,则移除列表中的墙。

删除一些实现细节我的实现如下所示:

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;
}

我的问题是我的迷宫没有完成,也没有遍历所有单元格。有时候只遍历了几个cell,几乎所有的cell都走完了。我相信我错过了一些东西,但无法弄清楚是什么。

请帮忙。

部分穿越迷宫请参见下图。

enter image description here

最佳答案

好吧,我解决了这个问题。这个纯Java问题,与算法无关。我比较了两堵墙。

public class Wall{

Point p1;
Point p2;
}

public class Point{
int x;
int y;
}

如果我使用 p1 和 p2 实现 Wall 类 equals() 和 hashCode()。然后在leftCell.rightWall 将等于 rightCell.leftWall,这就是问题所在。

关于java - 迷宫生成prim算法并不是所有的单元格都被遍历,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11459752/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com