Esempio n. 1
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);
        }