我尝试使用DFS编写迷宫解决方法,以找到通过生成的迷宫的路径。但是我遇到了麻烦。它甚至看起来都没有完成遍历。以下是样本运行的一些输出。迷宫看起来像这样:
+ +--+--+--+
| | |
+ +--+ + +
| | |
+--+--+--+ +
| | |
+ + + +--+
| | |
+--+--+--+ +
我的DFS方法产生了这个:
0 1 5 9
最后,我想要显示相同的迷宫,但是在其路径中有数字代表我访问过并通过它的顺序。
无论如何,这是我的代码:
public static void depthFirstSearch(){
boolean[] visited = new boolean[totalCells]; // marks which vertices have been visited during the search
Stack<Vertex> st = new Stack<Vertex>();
st.push(graph[0][0]);
while(!st.isEmpty()){
Vertex v = st.pop();
if(!visited[v.label]){
visited[v.label] = true;
System.out.print(v.label + " ");
// auxiliary stack to visit neighbors in the order which they appear
Stack<Vertex> auxStack = new Stack<Vertex>();
for(Vertex w : v.neighbors){
if(!visited[w.label]){
auxStack.push(w);
}
}
while(!auxStack.isEmpty()){
st.push(auxStack.pop());
}
}
}
System.out.println();
}
这也是顶点:
class Vertex{
int label;
int x;
int y;
boolean isVisited = false;
boolean hasNorthWall = true;
boolean hasSouthWall = true;
boolean hasEastWall = true;
boolean hasWestWall = true;
boolean hasAllWalls = true;
ArrayList<Vertex> neighbors = new ArrayList<Vertex>();
public Vertex(int x, int y){
this.x = x;
this.y = y;
}
}
我的构造函数:
public Maze(int size)
{
this.SIZE = size;
totalCells = SIZE * SIZE;
cellStack = new Stack<Vertex>();
graph = new Vertex[SIZE][SIZE];
}
提前感谢您的帮助!
编辑:添加邻居的分配方式。
public void assignNeighbors(Vertex v)
{
//This handles the cell north of current cell
if(v.y != 0)
{
v.neighbors.add(graph[v.x][v.y-1]);
}
//This handles the cell south of the current cell
if(v.y != (SIZE-1))
{
v.neighbors.add(graph[v.x][v.y+1]);
}
//This handles the cell left of the current cell
if(v.x != 0)
{
v.neighbors.add(graph[v.x -1][v.y]);
}
//right of the current
if(v.x != SIZE-1)
{
v.neighbors.add(graph[v.x + 1][v.y]);
}
}
EDIT2:添加标签的分配方式(它只存储顶点数)
public void fill()
{
int vertexNumber = 0;
//This loop creates a new vertex
for(int i=0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
Vertex v = new Vertex(j,i);
graph[j][i] = v;
}
}
//adds values to vertex
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
graph[j][i].label = vertexNumber;
vertexNumber++;
}
}
//This loop assigns the neighbors
for(int i = 0; i < SIZE; i++)
{
for(int j = 0; j < SIZE; j++)
{
assignNeighbors(graph[j][i]);
}
}
mazeGenerator();
}
答案 0 :(得分:0)
我对这部分不太确定
for(Vertex w : v.neighbors){
if(!visited[w.label]){
auxStack.push(w);
}
}
while(!auxStack.isEmpty()){
st.push(auxStack.pop());
}
如果我纠正了你可以用一个循环替换它,但这不应该是问题。你有没有尝试过一步一步的调试?你知道迷宫是怎么样的,因此你知道阿尔科特在每一步中应该如何表现。我建议你尝试一下然后更新你的帖子并描述你的算法在哪一步表现得很奇怪。
我想将此添加为评论,但我缺乏声誉。