1

我的问题是如何在 Java 中创建一个随机生成的迷宫?我知道创建迷宫的 DFS 方式的主要轮廓,但我很难实现它。在我的程序中,迷宫被保存在一个二维数组中,向数组加 1 会产生一个数组越界异常。我将如何避免这种情况?我不想做一个非常复杂的迷宫,只是一个简单的迷宫。虽然我已经开始创建代码,但我不知道如何使它工作。

DFS 方法的伪代码是:

create a CellStack (LIFO) to hold a list of cell locations  
set TotalCells = number of cells in grid  
choose a cell at random and call it CurrentCell  
set VisitedCells = 1  

while VisitedCells < TotalCells 
find all neighbors of CurrentCell with all walls intact   
      if one or more found 
          choose one at random  
          knock down the wall between it and CurrentCell  
          push CurrentCell location on the CellStack  
          make the new cell CurrentCell  
          add 1 to VisitedCells
      else 
          pop the most recent cell entry off the CellStack  
          make it CurrentCell
      endIf
    endWhile  

我不明白你怎么能知道你的邻居的墙壁是否完好无损以及如何摧毁它们。谁能给我一些关于这个程序的见解。非常感激。

4

1 回答 1

3

https://www.google.com/search?ix=seb&sourceid=chrome&ie=UTF-8&q=maze+generation+algorithm

有很多文献可以帮助你做到这一点。在这里重新散列是不公平的。

对于你问的两个问题。您的算法听起来很脆弱,因为它依赖于固定大小的数组。如果不是这样设计的,那么您将不得不使用调试器并找出它超出数组长度(array.length)的原因。至于第二个问题,您将使用简单的索引来查看相邻单元格。

  • 左侧迷宫的单元格[row][col-1]
  • 向右迷宫的单元格[row][col+1]
  • 迷宫上方的单元格[row-1][col]
  • 迷宫下方的单元格[row+1][col]

当然,您必须防止超出数组的边界,因为 row,col 位于迷宫的边缘。

判断是否有墙:

Cell cell = maze[row][col];
if( cell.isWall() ) ...
于 2012-03-21T02:43:54.873 回答