在图中遇到需要返回当前寻找的节点的路径问题的解决方法:
1、设置一个新from数组来存储父节点
2、在深度遍历的时候,将父节点存储到from中
3、将from换成stack(栈)来存储,然后通过一系列的栈操作来实现将栈中的值添加到一个新的vector向量中
3、编写show函数来展示新的vector向量的值
代码实现
template <class Graph> //查看路径
class Path{
private:
Graph &G; //引用一个编写好的图
int s; //source 原点
bool *visited; //判断是否已经遍历过了
int *from; //每访问一个节点,就储存节点父节点
void dfs(int v){
visited[v] = true;
typename Graph::adjIterator adj(G,v);
for(int i = adj.begin();!adj.end();i = adj.next()){
if(!visited){
from[i] = v; //i节点是从v这里过来的
dfs(i);
}
}
}
public:
Path(Graph &graph,int s):G(graph){
assert(s >=0 && s<G.V()); //原点是不越界的
visited = new bool[G.V()];
from = new int[G.V()];
for(int i=0;i<G.V();i++){
visited[i] = false;
from[i] = -1;
}
this->s = s;
dfs(s); //s相连接的所有的点通过from储存了起来
}
~Path(){
delete [] visited;
delete[] from;
}
bool hasPath(int w){ //是不是有路径
assert(w >= 0 && w<G.V());
return visited[w];
}
void path(int w,vector<int> &vec){
stack<int> s;
int p = w;
while (p != -1){
s.push(p);
p = from[p];
} //一步一步倒着 c从w往前推 直到推到了原节点(-1)
//把路径从stack取出来存进vector中
vec.clear();
while(!s.empty()){
vec.push_back(s.top());
s.pop();
} //将值添加进vec中
}
void showPath(int w){
vector<int> vec;
path(w, vec);
for(int i=0; i<vec.size();i++){
cout<<vec[i];
if(i == vec.size() -1){
cout<<endl;
}
else{
cout<<" -> ";
}
}
}
};