我目前已經(jīng)實現(xiàn)了 Dijkstra 的算法,但是當我用這樣的圖測試我的算法時出現(xiàn)了問題:并嘗試從 C 轉(zhuǎn)到 B。我知道為什么它不起作用。但是我想知道如果有這樣的圖表,正常的實現(xiàn)是否會起作用? 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),現(xiàn)在我沒有得到我在評論中提到的溢出。
1 回答

郎朗坤
TA貢獻1921條經(jīng)驗 獲得超9個贊
IsVisited
這里有點誤導(dǎo),因為您實際上可以訪問從源節(jié)點無法訪問的節(jié)點。我會把它重命名為isProcessed
. 要檢查您是否可以從源節(jié)點到達另一個節(jié)點,您需要檢查它的距離是否為int.maxVal
。
為避免溢出,當 currentVertex.ShortestDistanceFromTarget 為 時不要迭代鄰居int.maxVal
,因為它已經(jīng)是源節(jié)點無法訪問的節(jié)點。
- 1 回答
- 0 關(guān)注
- 176 瀏覽
添加回答
舉報
0/150
提交
取消