示例#1
0
        // A* search
        public static List <node> AS(string[,] aMap)
        {
            // initalising
            node startNode   = new node(startX, startY);
            node endNode     = new node(endX, endY);
            node currentNode = startNode;

            Dictionary <node, node> Parents       = new Dictionary <node, node>();
            List <node>             exploredNodes = new List <node>();

            // priority queue to sort by cost
            PriorityQueue <int, node> q = new PriorityQueue <int, node>();

            // add start node to begin
            startNode.totalCost = CalcCostAS(startNode, startNode);
            q.Enqueue(startNode.totalCost, startNode);

            while (!(q.IsEmpty))
            {
                // get next in queue
                currentNode = q.Dequeue();

                // finished once we find goal
                if (aMap[currentNode.X, currentNode.Y] == aMap[endNode.X, endNode.Y])
                {
                    return(tracePath(currentNode, Parents));
                }

                exploredNodes.Add(currentNode);

                foreach (node n in getNeighbours(currentNode, aMap))
                {
                    node newNode = n;

                    // calculating costs for algorithm
                    newNode.gCost     = currentNode.gCost + 1; // total movement from start if moving to next node is current + 1
                    newNode.totalCost = CalcCostAS(currentNode, newNode);

                    int ng = currentNode.gCost + CalcCostAS(currentNode, newNode);

                    if (!(exploredNodes.Contains(newNode)))
                    {
                        // only enqueued if not explored or in queue
                        if ((!(q.Contains(newNode))))
                        {
                            q.Enqueue(newNode.totalCost, newNode);
                        }

                        // only optimal path if cheaper cost
                        if (ng >= newNode.gCost)
                        {
                            Parents[newNode] = currentNode;
                        }
                    }
                }
            }
            return(tracePath(currentNode, Parents));
        }