我正在解决一个问题,我需要在给定的有向未加权图中找到两个节点之间的所有最短路径。我已经使用 BFS 算法来完成这项工作,但不幸的是我只能打印一条最短路径而不是全部,例如,如果它们是 4 条长度为 3 的路径,我的算法只打印第一个但我希望它打印所有四个最短路径。我想知道在下面的代码中,我应该如何更改它以便可以打印出两个节点之间的所有最短路径?
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
}
我非常感谢您的大力帮助谢谢,安德拉