我的问题是如何在Java中创建随机生成的迷宫?我知道DFS创建迷宫的主要方式,但我很难实现它。在我的程序中,迷宫保存在2D数组中,并且向数组中添加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
我不明白你怎么能知道你的邻居是否完好无损,以及如何摧毁他们。任何人都可以给我一些洞察这个程序。非常感激。
答案 0 :(得分:2)
https://www.google.com/search?ix=seb&sourceid=chrome&ie=UTF-8&q=maze+generation+algorithm
有很多文献可以帮助你做到这一点。在这里重复它并不是为了正义。
对于你提出的两个问题。您的算法听起来很脆弱,因为它依赖于固定大小的数组。如果它不是那样设计的,那么你必须抓住一个调试器并找出它超出数组长度的原因(array.length)。至于第二个问题,你将使用简单的索引来查看相邻的单元格。
当然,你必须防止越过数组的边界,因为row,col位于迷宫的边缘。
判断墙是否在这里:
Cell cell = maze[row][col];
if( cell.isWall() ) ...