我目前已经实现了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);
}
private static Stack<string> FormShortestPath(string targetPoint, Dictionary<string, Vertex> verticesDictionary)
{
Stack<string> traverseStack = new Stack<string>();
KeyValuePair<string, Vertex> vertex = verticesDictionary.Where(x => x.Key == targetPoint).FirstOrDefault();
while (vertex.Value.PreviousVertex != null)
{
traverseStack.Push(vertex.Value.PreviousVertex + " Goes To " + vertex.Key); //the end edge
vertex = verticesDictionary.Where(x => x.Key == vertex.Value.PreviousVertex).FirstOrDefault();
}
return traverseStack;
}
private static void InitializeVerticesDictionary(string sourcePoint, List<string> verticesStringList, Dictionary<string, Vertex> verticesDictionary)
{
foreach (string vertexString in verticesStringList)
{
Vertex vertex = new Vertex
{
ShortestDistanceFromTarget = int.MaxValue
};
if (vertexString == sourcePoint)
{
vertex.ShortestDistanceFromTarget = 0;
}
verticesDictionary.Add(vertexString, vertex);
}
}
更新:我将条件改为verticesDictionary.Values.ToList().Any(x => x.IsVisited == false && x.ShortestDistanceFromTarget != int.MaxValue)
,现在我没有收到我在评论中提到的溢出。
答案 0 :(得分:1)
IsVisited
这里有点误导,因为您实际上可以访问无法从源节点访问的节点。我会将其重命名为isProcessed
。要检查您是否可以从源节点到达另一个节点,您需要检查其距离是否为int.maxVal
。
为避免溢出,请不要在currentVertex.ShortestDistanceFromTarget为int.maxVal
时迭代邻居,因为它已经是来自源节点的无法访问的节点。