Ejemplo n.º 1
0
        /// <summary>
        /// Finds the shortest path between the specified nodes and returns it as a list of nodes.
        /// </summary>
        /// <param name="start">The starting node for the path</param>
        /// <param name="end">The ending node for the path</param>
        /// <returns>The path, represented as a list of nodes beginning with start and ending with end.</returns>
        public List <Node> FindPath(Node start, Node end)
        {
            BinaryHeap pq = new BinaryHeap(Nodes.Length);

            foreach (Node n in Nodes)
            {
                if (n == start)
                {
                    n.NodeCost = 0;
                }
                else
                {
                    n.NodeCost = Double.PositiveInfinity;
                }
                n.Predecessor = null;
                pq.Add(n, n.NodeCost);
            }
            while (pq.Count != 0)
            {
                Node n = pq.ExtractMin();
                if (n == end)
                {
                    break;
                }
                foreach (UndirectedEdge v in n.Edges)
                {
                    Node temp;
                    if (v.A == n)
                    {
                        temp = v.B;
                    }
                    else
                    {
                        temp = v.A;
                    }
                    double w       = v.Cost;
                    double newCost = w + n.NodeCost;
                    if (newCost < temp.NodeCost)
                    {
                        pq.DecreasePriority(temp, newCost);
                        temp.NodeCost    = newCost;
                        temp.Predecessor = n;
                    }
                }
            }
            Stack <Node> s = new Stack <Node>();
            Node         t = end;

            s.Push(t);
            while (t.Predecessor != null)
            {
                s.Push(t.Predecessor);
                t = t.Predecessor;
            }
            List <Node> l = new List <Node>();

            while (s.Count != 0)
            {
                l.Add(s.Pop());
            }
            return(l);
        }