亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Dijkstra 算法:如果有 2 個未連接的圖,它應該工作嗎?

Dijkstra 算法:如果有 2 個未連接的圖,它應該工作嗎?

C#
慕容3067478 2021-06-28 09:16:24
我目前已經實現了 Dijkstra 的算法,但是當我用這樣的圖測試我的算法時出現了問題:并嘗試從 C 轉到 B。我知道為什么它不起作用。但是我想知道如果有這樣的圖表,正常的實現是否會起作用?  internal static Stack<string> Dijkstra(string sourcePoint, string targetPoint, Graph graph)    {        List<string> verticesStringList = graph.GetAllVertices();        Dictionary<string, Vertex> verticesDictionary = new Dictionary<string, Vertex>();        InitializeVerticesDictionary(sourcePoint, verticesStringList, verticesDictionary);        while (verticesDictionary.Values.ToList().Any(x => x.IsVisited == false))        {            KeyValuePair<string, Vertex> keyValuePair = verticesDictionary.Where(x => x.Value.IsVisited == false).ToList().Min();            string vertexKey = keyValuePair.Key;            Vertex currentVertex = keyValuePair.Value;            List<string> neighbourVertices = graph.GetNeighbourVerticesSorted(keyValuePair.Key);            foreach (string neighbourVertexString in neighbourVertices)            {                Vertex neighbourVertex = verticesDictionary[neighbourVertexString];                int newDistanceFromStartVertex = currentVertex.ShortestDistanceFromTarget + graph.GetEdgeWeight(keyValuePair.Key, neighbourVertexString);                if (newDistanceFromStartVertex < neighbourVertex.ShortestDistanceFromTarget)                {                    verticesDictionary[neighbourVertexString].ShortestDistanceFromTarget = newDistanceFromStartVertex;                    verticesDictionary[neighbourVertexString].PreviousVertex = keyValuePair.Key;                }            }            verticesDictionary[vertexKey].IsVisited = true;        }        return FormShortestPath(targetPoint, verticesDictionary);    }更新:我改變了我的條件verticesDictionary.Values.ToList().Any(x => x.IsVisited == false && x.ShortestDistanceFromTarget != int.MaxValue),現在我沒有得到我在評論中提到的溢出。
查看完整描述

1 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

IsVisited這里有點誤導,因為您實際上可以訪問從源節點無法訪問的節點。我會把它重命名為isProcessed. 要檢查您是否可以從源節點到達另一個節點,您需要檢查它的距離是否為int.maxVal。

為避免溢出,當 currentVertex.ShortestDistanceFromTarget 為 時不要迭代鄰居int.maxVal,因為它已經是源節點無法訪問的節點。


查看完整回答
反對 回復 2021-07-10
  • 1 回答
  • 0 關注
  • 184 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號