猿问

Dijkstra 算法:如果有 2 个未连接的图,它应该工作吗?

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


慕容3067478
浏览 154回答 1
1回答

郎朗坤

IsVisited这里有点误导,因为您实际上可以访问从源节点无法访问的节点。我会把它重命名为isProcessed.&nbsp;要检查您是否可以从源节点到达另一个节点,您需要检查它的距离是否为int.maxVal。为避免溢出,当 currentVertex.ShortestDistanceFromTarget 为 时不要迭代邻居int.maxVal,因为它已经是源节点无法访问的节点。
随时随地看视频慕课网APP
我要回答