我知道這通常是用做廣度第一,但我們被要求既要做到這一點,我已經完成廣度優先....深度優先搜索找到最短路徑?
我覺得這是一個使用深度優先搜索的一個非常典型的例子,所以我希望能夠在這裏得到一些幫助......我試圖通過使用深度優先搜索來找到通過迷宮的最短路徑,但截至目前我無法圍繞着如何完成它。這是到目前爲止我的代碼:
void maze::findPathRecursive(graph &g, int position, int goal) {
if (position == goal) {
isPath = true; //returns true if there is a path to the goal
correctPath.push_back(position); // the path to the goal
} else {
g.mark(position);
g.visit(position);
//gets all the neighbors of the current position
vector<int> neighbors = getNeighbors(position, g);
while (!neighbors.empty()) {
int n = neighbors.back();
neighbors.pop_back();
if (!g.isVisited(n)) {
findPathRecursive(g, n, goal);
}
if (isPath) {
correctPath.push_back(position);
break;
}
}
}
}
眼下,這是什麼做的是找到從那裏的目標和休息的第一路徑就可以了。我知道我需要擺脫休息時間,並試圖製作另一個矢量來存儲最短路徑,並比較它和之前最短的路徑之間的長度,但它不起作用,因爲我覺得我需要在某個點但無法弄清楚在這裏如何做到這一點。
任何幫助非常感謝!
g是一個包含迷宮的圖形。
你能確認你的圖是否是非循環的嗎? – nobillygreen
@nobillygreen現在它的工作方式是,即使它確實做了一個大圓圈,第一個節點將被標記爲已訪問並且將不能被再次訪問,所以在某種意義上,它是 – seanscal