如何在修改后的BFS程序中解决无限循环?

时间:2019-04-17 17:54:38

标签: c++ breadth-first-search

我已经建立了一个代码,该代码将基于与节点之间每个边相关联的值浏览图形。每个边缘都有与之关联的颜色和类型,并且如果颜色或类型与最后一个颜色或类型匹配,则仅应遵循BFS中的一条边缘。第一个颜色/类型由跟随的第一个边设置。但是,当我运行自己的特定代码时,在安装程序中的某个地方出现了无限循环,该循环无法解决。

我尝试设置不同的循环样式,并使用迭代器而不是当前的for循环遍历列表,但均无效,并且都导致相同的错误。

队列Q;

Q.push(neededNode);
string lastType = "";
string lastColor = "";
while (!Q.empty()){
    node u = Q.front();
    Q.pop();
    for(auto& itr : adjacencyList[u.city]){ //cycle through the adjacency list
        for (auto& entry: nodeList){ //find the node for the entry
            if (entry.city == (itr).city){
                //Initial condition for setting color/type to follow
                if(lastType == "" || lastColor == ""){
                    lastColor = (itr).color;
                    lastType = (itr).type;
                    entry.state = true;
                    entry.distance = u.distance +1;
                    entry.parent = u.city;
                    cout << u.city << " " << lastColor << " " << lastType << endl;
                //If Types match
                }else if(lastType == (itr).type){
                    lastColor = (itr).color;
                    lastType = (itr).type;
                    entry.state = true;
                    entry.distance = u.distance +1;
                    entry.parent = u.city;
                    cout << u.city << " " << lastColor << " " << lastType << endl;
                //If colors match
                }else if(lastColor == (itr).color){
                    lastColor = (itr).color;
                    lastType = (itr).type;
                    entry.state = true;
                    entry.distance = u.distance +1;
                    entry.parent = u.city;
                    cout << u.city << " " << lastColor << " " << lastType << endl;
                }
                Q.push(entry);
            }
        }
    }
}

理想情况下,代码应该运行并在完成后停止运行,而且我应该能够遵循父级值到达正确的路径。目前,我遇到了无限循环。

1 个答案:

答案 0 :(得分:0)

标记您已经看到的节点,以确保您不会再次访问它们,例如,使用.state:

if (entry.city == (itr).city && !entry.state) {
    //Initial condition for setting color/type to follow