예제 #1
0
        /*
         * Time((V+E)logV), Space(V)
         * can't handle negative distances; can return shortest paths from vertex 0 to all other vertice.
         * 1. initialize the distance of vetex 0 to 0 and all others to INF.
         * 2. add all vertice to a minimum heap based on their distances from vetex 0
         * 2. loop until heap is empty, extract min from heap and update the distance of its all adjacent vertices.
         */
        int[] Dijkstra(int n, IList <int[]>[] adj)
        {
            var dist = new int[n];

            for (int i = 1; i < n; i++)
            {
                dist[i] = INF;
            }
            var heap = new HeapArray(dist);

            var prev = new int[n]; // used to recover the path

            for (int i = 0; i < n - 1; i++)
            {
                var min = heap.ExtractMin();
                foreach (var e in adj[min])
                {
                    int src = e[0], dst = e[1], w = e[2];
                    if (dist[dst] > dist[src] + w)
                    {
                        heap.Update(dst, dist[src] + w);
                        dist[dst] = dist[src] + w;
                        prev[dst] = src;
                    }
                }
            }

            return(dist);
        }