[英]Java- Maze Breadth First Search Shortest Path
我似乎在理解如何檢索我正在實現的廣度優先搜索算法發現的最短路徑時遇到問題。 目前,算法可以正常工作,因為它可以找到迷宮的出口,如果它可以到達它。 在另一篇文章中,有人提到在節點被標記為已訪問后保持對父進程的攻擊。 我嘗試了一個簡單的實現,試圖通過在Point結構中包含一個父Point來跟蹤父項,但是當我在Grid上標記路徑時它標記了它迄今為止已經過去的所有路徑,我相信我可能搞砸了以某種方式跟蹤父母。
任何人都知道我哪里出錯了。 也許我錯過了一些簡單的東西? 該守則包含在下面作為參考。
迷宮是2D整數網格。 假設1是牆,0是可移動路徑。
Point類包含:Point Parent int x,y; 僅此而已。
public Point BFS(int x, int y){
Queue<Point> Path = new Queue<>();
Path.enqueue(new Point(x,y));//push current on queue
Point Cur = Path.front();//make current point
//test code for recursive backcall of path
Cur.setParent(null);
//test code for recursive backcall of path
Point end = new Point(mWidth-2, mHeight-2);//set goal
while((!Path.isEmpty())){
Point old = Cur;
Cur = Path.dequeue();
Cur.setParent(old);
if(Cur.compareto(end)){
return Cur;//return Point then traverse up from here calling Cur.Parent to get path.
}
else if(Maze[Cur.getX()][Cur.getY()]==1){//Enque all possible paths
Maze[Cur.getX()][Cur.getY()] = 2;//mark as visitied
if(Cur.getX()-1>=0)
if(Maze[Cur.getX()-1][Cur.getY()]==1)
Path.enqueue(new Point(Cur.getX()-1,Cur.getY()));
if(Cur.getX()+1<mWidth)
if(Maze[Cur.getX()+1][Cur.getY()]==1)
Path.enqueue(new Point(Cur.getX()+1,Cur.getY()));
if(Cur.getY()-1>=0)
if(Maze[Cur.getX()][Cur.getY()-1]==1)
Path.enqueue(new Point(Cur.getX(),Cur.getY()-1));
if(Cur.getY()+1<mHeight)
if(Maze[Cur.getX()][Cur.getY()+1]==1)
Path.enqueue(new Point(Cur.getX(),Cur.getY()+1));
}
}
return null;
}
看起來old
在多次迭代后不再是父級。 您可以在將該點添加到隊列時設置父級,例如:
Point next = new Point(Cur.getX()-1,Cur.getY());
next.setParent(Cur);
Path.enqueue(next);
然后,當您找到結束時,您應該能夠通過調用getParent()將路徑返回到開頭,直到它為null
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.