我正在研究一個問題,我需要在給定的有向未加權圖中找到兩個節點之間的所有最短路徑。我使用BFS算法來完成這項工作,但不幸的是,我只能打印一條最短路徑,而不是全部,例如,如果它們是4條長度爲3的路徑,我的算法只打印第一條路徑,但我希望打印所有路徑四條最短路徑。我在下面的代碼中想知道如何更改它,以便可以打印出兩個節點之間的所有最短路徑?使用BFS算法在未加權的有向圖中找到兩個節點之間的所有最短路徑
class graphNode{
public:
int id;
string name;
bool status;
double weight;
};
map<int, map<int,graphNode>* > graph;
int Graph::BFS(graphNode &v, graphNode &w){
queue <int> q;
map <int, int> map1; // this is to check if the node has been visited or not.
std::string str= "";
map<int,int> inQ; // just to check that we do not insert the same iterm twice in the queue
map <int, map<int, graphNode>* >::iterator pos;
pos = graph.find(v.id);
if(pos == graph.end()) {
cout << v.id << " does not exists in the graph " <<endl;
return 1;
}
int parents[graph.size()+1]; // this vector keeps track of the parents for the node
parents[v.id] = -1;
if (findDirectEdge(v.id,w.id) == 1){
cout << " Shortest Path: " << v.id << " -> " << w.id << endl;
return 1;
} //if
else{
int gn;
map <int, map<int, graphNode>* >::iterator pos;
q.push(v.id);
inQ.insert(make_pair(v.id, v.id));
while (!q.empty()){
gn = q.front();
q.pop();
map<int, int>::iterator it;
cout << " Popping: " << gn <<endl;
map1.insert(make_pair(gn,gn));
if (gn == w.id){//backtracing to print all the nodes if gn is the same as our target node such as w.id
int current = w.id;
cout << current << " - > ";
while (current!=v.id){
current = parents[current];
cout << current << " -> ";
}
cout <<endl;
}
if ((pos = graph.find(gn)) == graph.end()) {
cout << " pos is empty " <<endl;
continue;
}
map<int, graphNode>* pn = pos->second;
map<int, graphNode>::iterator p = pn->begin();
while(p != pn->end()) {
map<int, int>::iterator it;
it = map1.find(p->first);//map1 keeps track of the visited nodes
graphNode gn1= p->second;
if (it== map1.end()) {
map<int, int>::iterator it1;
it1 = inQ.find(p->first); //if the node already exits in the inQ, we do not insert it twice
if (it1== inQ.end()){
parents[p->first] = gn;
cout << " inserting " << p->first << " into the queue " <<endl;
q.push(p->first); // add it to the queue
} //if
} //if
p++;
} //while
} //while
}
我很欣賞你的所有幫助很大 謝謝, 安德拉
你的算法是正確的,但措詞不當,很容易與拓撲排序混淆,這與最短路徑無關。 – CaptainCodeman 2014-05-22 14:12:35