图形遍历问题
Graph Traversal Problem
My Dijkstra算法可以很好地查找路径。现在我想回去看看我走的路。我标记了一个访问过的顶点,并给它一个指向我来自"prev"的顶点的指针。不幸的是,在while循环中循环时,这些指针会以某种方式被操纵,因此末端的顶点不知道它们来自哪里。你能帮我吗?
可能是我不明白的指针问题。我有一个复制构造函数和一个=运算符。
int MyMatrix::searchBreadth(MyVertex &from,MyVertex &to,int mode)
{
queue<MyVertex> q;//queue
vector<MyVertex> nb;//vector of neighbours
path=INFINITY;//path is very long
visits.push_back(from.getName());
from.setDistance(0);
MyVertex n("start");
from.setPrev(n);
q.push(from);
while(!q.empty())
{
MyVertex v=q.front();
q.pop();
int k=v.getDistance();
nb.clear();
nb = getNeighbours(v);
for(unsigned int i=0;i<nb.size();i++)
{
if((!nb[i].getPrev())&&path==INFINITY) nb[i].setPrev(v);
if(!mode){//unweighted
if(!wasVisited(nb[i].getName())){
nb[i].setDistance(k+1);
q.push(nb[i]);
}
}
if(mode){//length or weight
if(!wasVisited(nb[i].getName())){
int cost=0;
MyEdge e = m->getEdge(v,nb[i]);
if(mode==1)cost=(int) e.getLength();//length
if(mode==2)cost=(int) e.getWeight();//weigth
nb[i].setDistance(k+cost);
q.push(nb[i]);
}
}
if((nb[i].getName().compare(to.getName())==0) && (!wasVisited(nb[i].getName()))){//path found
int j=nb[i].getDistance();
if(j<path)path=j;
}
visits.push_back(nb[i].getName());
}//end of for
//end of 0size if
}//end of while
return path;
}
MyVertex::MyVertex()
{
name="null";
dist=0;
visited=false;
prev=0;
}
MyVertex::MyVertex(string name)
{
this->name=name;
visited=false;
dist=numeric_limits<int>::max();
prev=0;
}
MyVertex::~MyVertex(void)
{
if (!prev) prev=0;
}
MyVertex::MyVertex(const MyVertex& V){
this->name = V.name;
this->visited=V.visited;
this->dist=V.dist;
this->prev=V.prev;
}
MyVertex& MyVertex::operator=(const MyVertex& L){
if (this == &L){ return *this;
}else{
delete prev;
dist=L.dist;
name=L.name;
visited=L.visited;
prev=L.prev;
}
return *this;
}
您遗漏了很多代码,但您似乎在调整节点的Distance
并设置其prev
,而没有首先检查它是否已经有一个较小的Distance
。一旦找到任何路径,就停止设置prev
,这样,如果以后找到较短的路径,则可能不会标记其节点。
相关文章:
- 有什么方法可以遍历结构吗
- 在循环中按顺序遍历成员变量
- 遍历模板参数
- 在遍历处理程序的向量时注册和注销处理程序
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 遍历并行数组以确定C++中的最大数字
- 遍历顺序由 std::文件系统directory_iterator给出
- 遍历链表时的无限循环
- 在使用 In Order 遍历成员函数时引发异常(堆栈溢出)时出现问题
- 循环遍历向量<string>并保持每个元素"count"时出现问题
- 如何修复关卡顺序遍历问题(二叉树)的无限循环错误
- 如果使用迭代器,如何解决遍历列表的问题
- 遍历 QHash 并提取重复值的键时遇到问题
- 遍历目录递归问题
- 指针问题C++,未正确遍历
- 使用链表转换稀疏矩阵(遍历问题)
- 线程内二叉树的插入或顺序遍历有什么问题
- 遍历类向量导致问题
- 遍历C++中的字符串列表,出了什么问题?
- 图形遍历问题