Esempio n. 1
0
        public Kruskal(WeightedEdgeGraph G)
        {
            queue = new Queue <WeightedEdge>();
            pq    = new MinPQ <WeightedEdge>(G.GetE());
            union = new int[G.GetV()];
            for (int x = 0; x < union.Count(); x++)//初始化连通分量
            {
                union[x] = x;
            }
            foreach (var e in G.edges())//初始化优先队列
            {
                pq.insert(e);
            }

            while (!pq.IsEmpty() && queue.Count < G.GetV() - 1)
            {
                var minE = pq.DeletePQHead();//最短边
                int v    = minE.either();
                int w    = minE.other(v);
                if (isConnect(v, w))
                {
                    continue;                 //会形成环
                }
                queue.Enqueue(minE);
                connect(v, w);//加入同一连通分量
            }
        }
Esempio n. 2
0
        private static IEnumerable <int> FindPath(Galaxy galaxy, int start, int end)
        {
            //start a heap the size of the galaxy
            PQ pq = new PQ(galaxy.Size);

            //distance array to each star
            float[] distances = new float[galaxy.Size];
            int[]   previous  = new int[galaxy.Size];
            distances[start] = 0;

            for (int i = 0; i < galaxy.Size; i++)
            {
                if (i != start)
                {
                    distances[i] = Mathf.Infinity;
                }
                pq.AddWithPriority(i, distances[i]);
            }

            bool searching = true;

            while (searching)
            {
                var         currentSearchingIndex = pq.GetLowest().value;
                SolarSystem currentSolarSystem    = galaxy.solarSystems[currentSearchingIndex];
                for (int i = 0; i < currentSolarSystem.linkedSystemIndex.Count; i++)
                {
                    int   otherIndex  = currentSolarSystem.linkedSystemIndex[i];
                    float newDistance = distances[currentSearchingIndex] + currentSolarSystem.links[otherIndex].Distance;
                    if (newDistance < distances[otherIndex])
                    {
                        distances[otherIndex] = newDistance;
                        previous[otherIndex]  = currentSearchingIndex;
                        pq.DecreasePriority(otherIndex, newDistance);
                    }
                }

                searching = !pq.IsEmpty() && distances[end] > pq.Peek().priority;
            }
            var sequence = new Stack <int>();
            int target   = end;

            while (target != start)
            {
                sequence.Push(target);
                target = previous[target];
            }
            return(sequence);
        }