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变量有关,但我不确定。任何人都可以帮我找出我的错误,我一直在试图找到它,但无济于事。非常感激!麻烦创建一个DFS迷宫
把'String Maze [] [] = new String [20] [20]'改成'char Maze [] [] = new char [20] [20]':那么你可以使用'... == '#''而不是'... equals(“#”)' – 2012-04-11 13:48:54
注意命名约定......命名变量时,第一个单词不是大写,后面的单词是。另外,除非明确声明为'final'(指的是'NORTH','SOUTH','EAST'和'WEST'变量),否则不要大写变量名的每个字母。 – fireshadow52 2012-04-11 14:05:20