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