我目前已经实现了 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),现在我没有得到我在评论中提到的溢出。
郎朗坤
相关分类