簡體   English   中英

如何在我修改的BFS程序中解決無限循環?

[英]How to resolve an Infinite loop in my modified BFS program?

我已經設置了一個代碼,該代碼將基於與節點之間的每個邊緣相關聯的值來導航圖形。 每條邊都有一個與之相關的顏色和類型,如果顏色或類型與最后一種顏色或類型匹配,我應該只跟隨BFS中的邊。 第一個顏色/類型由遵循的第一個邊緣設置。 但是,當我運行我的特定代碼時,我在設置中的某個地方得到一個無法解決的infite循環。

我已經嘗試設置不同的循環樣式並使用迭代器而不是當前的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);
            }
        }
    }
}

理想情況下,代碼應該在完成時運行並停止運行,並且我應該能夠將父值跟隨到正確的路徑。 目前,我得到一個無限循環。

標記您已經看過的節點,確保您不再訪問它們(例如使用.state):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM