import java.util.*;
public class MazeGenerator
{
public void init()
{
String Maze[][] = new String [20][20];
for (int i =0; i <20; i++) {
for (int j = 0; j < 20; j++) {
Maze[i][j] = "#";
}
}
generate(Maze);
for (int i =0; i <20; i++) {
for (int j = 0; j < 20; j++) {
System.out.print(" " + Maze[i][j]);
}
System.out.println("");
}
}
public void generate (String Maze[][])
{
Stack <String> CellStack = new Stack<String>();
int TotalCells = Maze.length * Maze.length;
int x = 10, y = 10;
String CurrentCell = Maze[x][y];
Maze[x][y] = "-";
CellStack.push(CurrentCell);
int VisitedCell = 1;
boolean EastT, WestT, NorthT, SouthT;
while(VisitedCell < TotalCells)
{
String EAST = Maze[x+1][y];
String WEST = Maze[x-1][y];
String NORTH = Maze[x][y+1];
String SOUTH = Maze[x][y-1];
if(EAST == "#")
EastT = true;
else
EastT = false;
if(WEST == "#")
WestT = true;
else
WestT = false;
if(NORTH == "#")
NorthT = true;
else
NorthT = false;
if(SOUTH == "#")
SouthT = true;
else
SouthT = false;
if(WestT == true || EastT == true || NorthT == true || SouthT == true)
{
double Random = (int) (Math.random() * 4) + 1;
switch ((int) Random)
{
case 1:
if(EastT == true){
CurrentCell = EAST;
break;
}
else
break;
case 2:
if(WestT == true){
CurrentCell = WEST;
break;
}
else
break;
case 3:
if(NorthT == true){
CurrentCell = NORTH;
break;
}
else
break;
case 4:
if(SouthT == true){
CurrentCell = SOUTH;
break;
}
else
break;
}
CurrentCell = "-";
CellStack.push(CurrentCell);
VisitedCell++;
}
else
{
CurrentCell = CellStack.pop();
}
}
}
}
当我打印出来时,我得到一个迷宫,里面全是“#”(第一个位置有一个“-”),这意味着迷宫没有以正确的方式创建。但我不明白为什么它不起作用。我认为这可能与 CurrentCell 变量有关,但我不确定。谁能帮我找出我的错误,我一直在尝试找到它但无济于事。非常感激!
最佳答案
好的。这并不能完全修复您的程序,但可以修复代码中的问题:
您对 if(EAST == "#")
(或类似命令)进行了大量测试。但是,您不能将 ==
与字符串一起使用,因为这会比较它们的引用。您必须使用.equals()
。因此,您可以使用:if(EAST.equals("#"))
。
我也不明白你在哪里更改 Maze[][] 数组的内容。看起来就像您正在编辑堆栈,但忽略了最后打印的数组。
风格调整:
如果您有 boolean 变量(我们称之为
var
),则不必使用if(var == true)
,而是使用if(var)
。不要使用 if/else 语句来分配 boolean 变量。例如:
if(WEST == "#") WestT = true; else WestT = false;
可以简化为:
WestT = WEST.equals("#");
关于java - 创建 DFS 迷宫时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9778546/