public static void RunExample()
        {
            //First, we create the priority queue.
            SimplePriorityQueue<string> priorityQueue = new SimplePriorityQueue<string>();

            //Now, let's add them all to the queue (in some arbitrary order)!
            priorityQueue.Enqueue("4 - Joseph", 4);
            priorityQueue.Enqueue("2 - Tyler", 0); //Note: Priority = 0 right now!
            priorityQueue.Enqueue("1 - Jason", 1);
            priorityQueue.Enqueue("4 - Ryan", 4);
            priorityQueue.Enqueue("3 - Valerie", 3);

            //Change one of the string's priority to 2.  Since this string is already in the priority queue, we call UpdatePriority() to do this
            priorityQueue.UpdatePriority("2 - Tyler", 2);

            //Finally, we'll dequeue all the strings and print them out
            while(priorityQueue.Count != 0)
            {
                string nextUser = priorityQueue.Dequeue();
                Console.WriteLine(nextUser);
            }

            //Output:
            //1 - Jason
            //2 - Tyler
            //3 - Valerie
            //4 - Joseph
            //4 - Ryan

            //Notice that when two strings with the same priority were enqueued, they were dequeued in the same order that they were enqueued.
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generar el árbol SPF de la topología en un proyecto, tomando el parámetro como punto de origen
        /// </summary>
        /// <param name="idRouterOrigen"></param>
        /// <param name="idProyecto"></param>
        /// <returns></returns>
        public static SimplePriorityQueue<NodoDijkstra> GenerarRutas(NodoDijkstra idRouterOrigen, int idProyecto)
        {
            idRouterOrigen.nMinDistancia = 0.0;
            SimplePriorityQueue<NodoDijkstra> routerQueue = new SimplePriorityQueue<NodoDijkstra>();
            routerQueue.Enqueue(idRouterOrigen, 1);

            while (routerQueue.Count > 0)
            {
                NodoDijkstra currentRouter = routerQueue.Dequeue();
                //Visita cada enlace adyacente al router u
                foreach (var enlace in currentRouter.listaEnlaces)
                {
                    NodoDijkstra vecino = new NodoDijkstra(enlace.idRouterB, idProyecto);
                    double nPesoBandwidth = enlace.nBandwidth;
                    double nDistanciaTotal = currentRouter.nMinDistancia + nPesoBandwidth;
                    if (nDistanciaTotal < vecino.nMinDistancia)
                    {
                        routerQueue.Remove(vecino);
                        vecino.nMinDistancia = nDistanciaTotal;
                        vecino.idRouterPrevio = currentRouter;
                        routerQueue.Enqueue(vecino, 1);
                    }
                }
            }
            return routerQueue;
        }
    public AStarSearch(WeightedGraph<Position> graph, Position start, Position goal)
    {
        var frontier = new SimplePriorityQueue<Position>();
        frontier.Enqueue(start, 0);

        cameFrom[start] = start;
        costSoFar[start] = 0;

        while (frontier.Count > 0)
        {
            var current = frontier.Dequeue();

            if(current.Equals(goal))
            {
                break;
            }

            foreach (var next in graph.Neighbors(current))
            {
                int newCost = costSoFar[current] + graph.Cost(current, next);
                if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])
                {
                    costSoFar[next] = newCost;
                    int priority = newCost + Heuristic(next, goal);
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }
        } 
    }
Ejemplo n.º 4
0
	public Queue<Vector2> GetPath(Node start, Node goal)
    {
        List<Node> closedSet = new List<Node>();  // The set of nodes already evaluated
        SimplePriorityQueue<Node> openSet = new SimplePriorityQueue<Node>(); // The set of tentative nodes to be evaluated
        openSet.Enqueue(start, 0);
        Dictionary<Node, Node> came_from = new Dictionary<Node, Node>();

        Dictionary<Node, float> g_score = new Dictionary<Node, float>();
        
        Dictionary<Node, float> f_score = new Dictionary<Node, float>();

        foreach (Node node in graph.nodes.Values)
        {
            g_score[node] = Mathf.Infinity;
            f_score[node] = Mathf.Infinity;
        }
        g_score[start] = 0f;
        f_score[start] = heuristic_cost_estimate(start, goal);

        while(openSet.Count > 0)
        {
            Node current = openSet.Dequeue();
            
            if(current == goal )
            {
                return reconstruct_path(came_from, current);
            }
            closedSet.Add(current);

            foreach(Node neighbour in current.edges.Keys)
            {
                
                if (closedSet.Contains(neighbour))
                    continue;
                float tentative_g_score = g_score[current] + dist_between(current, neighbour); // length of this path.
                if (openSet.Contains(neighbour) && tentative_g_score >= g_score[neighbour])
                {
                    continue;
                }
                came_from[neighbour] = current;
                g_score[neighbour] = tentative_g_score;
                f_score[neighbour] = g_score[neighbour] + heuristic_cost_estimate(neighbour, goal);
                openSet.Enqueue(neighbour, f_score[neighbour]);
            }
        }
        // Failed to find a path.
        return null;
    }
Ejemplo n.º 5
0
        public Room a_star(Room room)
        {
            Node current = new Node(room);

            current.updateCosts();
            Node next = null;

            //main loop
            while (current.getFinal() > GRADE_THRESHOLD)
            {
                //create all nodes for search in a priority queue.
                createNeighbourNodes(current, room.doorPlacement);

                //retrieve "closest node"
                next    = priorityQueue.Dequeue();
                current = next;
            }
            return(current._room);
        }
Ejemplo n.º 6
0
        private bool Search()                             //main function
        {
            while (frontier.Count != 0)                   //while there are nodes left to check
            {
                Node current = frontier.Dequeue();        //fetches the node with the best (lowest) movement cost which wasnt checked
                current.State = NodeState.Closed;         //marks it as checked ("closed")

                if (current.Location.Equals(this.finish)) //if end was reached, break
                {
                    return(true);
                }

                foreach (Node n in GetNearbyNodes(current)) //fetches adjecent nodes to the one currently tested
                {
                    frontier.Enqueue(n, n.F);               //adds each to the frontier
                }
            }
            return(false);
        }
    public Dictionary <int, StructuredAlias> .ValueCollection generateAliasOnTheFly()
    {
        mainMap          = ParameterManager.Instance.MapToPlay;
        gridType         = ParameterManager.Instance.GridType;
        SimilarMapsQueue = new SimplePriorityQueue <TileObject[, ]>();
        K_CollisionSet   = MapEvaluator.BuildKCollisionVec(mainMap, gridType, ParameterManager.Instance.StartCell, Mathf.Max(ParameterManager.Instance.minStepsSolution, ParameterManager.Instance.maxStepsSolution));
        GenerateAndTestAliasMaps();
        Dictionary <int, StructuredAlias> dic = new Dictionary <int, StructuredAlias>();

        int i = UnityEngine.Random.Range(3, 7); //try to change

        while (i > 0)
        {
            dic.Add(i, new StructuredAlias(SimilarMapsQueue.Dequeue()));
            i--;
        }

        return(dic.Values);
    }
Ejemplo n.º 8
0
        public override IList <GridNode> Search(GridNode start, GridNode goal,
                                                Motility motility)
        {
            Dictionary <GridNode, GridNode> parentMap = new Dictionary <GridNode, GridNode>();
            SimplePriorityQueue <GridNode>  frontier  = new SimplePriorityQueue <GridNode>();

            frontier.Enqueue(start, start.PathCost);

            while (frontier.Count > 0)
            {
                GridNode current = frontier.Dequeue();

                if (current == goal)
                {
                    break;
                }

                foreach (GridNode neighbor in current.Neighbors)
                {
                    IPathfindingEdge edge = current.JoiningEdge(neighbor);

                    //if (!IsTraversable(edge, motility)) continue; // TODO: Make this unnecessary

                    float newCost      = current.PathCost + edge.Weight;
                    float neighborCost = neighbor.PathCost;
                    bool  containsKey  = parentMap.ContainsKey(neighbor);

                    if (containsKey && (newCost >= neighborCost))
                    {
                        continue;
                    }

                    neighbor.PathCost   = newCost;
                    parentMap[neighbor] = current; // UPSERT dictionary function
                    float priority = newCost;
                    frontier.Enqueue(neighbor, priority);
                }
            }

            IList <GridNode> path = ReconstructPath(parentMap, start, goal);

            return(path);
        }
Ejemplo n.º 9
0
        private bool FindPath(Cell start, Cell goal)
        {
            frontier.Clear();

            cameFrom.Clear();

            costSoFar.Clear();

            frontier.Enqueue(start, 0);

            cameFrom[start] = start;

            costSoFar[start] = 0;

            while (frontier.Count > 0)
            {
                var current = frontier.Dequeue();

                if (current == goal)
                {
                    return(true);
                }

                foreach (var next in GetNeighbors(current, goal))
                {
                    int newCost = costSoFar[current] + 1;

                    if (!costSoFar.ContainsKey(next) || newCost < costSoFar[next])
                    {
                        costSoFar[next] = newCost;

                        int priority = newCost + Heuristic(next, goal);

                        frontier.Enqueue(next, priority);

                        cameFrom[next] = current;
                    }
                }
            }

            return(false);
        }
Ejemplo n.º 10
0
        public int Solve()
        {
            Init();

            while (priorityQueue.Count > 0)
            {
                int place = priorityQueue.Dequeue();

                List <int> neighbours = GetNeighbourPlaces(place);

                foreach (int neighbour in neighbours)
                {
                    int routeMinH = placeDatas[place].RouteMinH;
                    int routeMaxH = placeDatas[place].RouteMaxH;

                    if (placeDatas[neighbour].H < routeMinH)
                    {
                        routeMinH = placeDatas[neighbour].H;
                    }

                    if (placeDatas[neighbour].H > routeMaxH)
                    {
                        routeMaxH = placeDatas[neighbour].H;
                    }

                    int routeDiff = Math.Abs(routeMaxH - routeMinH);

                    if (routeDiff < placeDatas[neighbour].RouteHeightDiff)
                    {
                        placeDatas[neighbour].RouteHeightDiff = routeDiff;
                        placeDatas[neighbour].PreviousPlace   = place;

                        placeDatas[neighbour].RouteMinH = routeMinH;
                        placeDatas[neighbour].RouteMaxH = routeMaxH;

                        priorityQueue.Enqueue(neighbour, routeDiff);
                    }
                }
            }

            return(GetTotalHeightDifference());
        }
Ejemplo n.º 11
0
        public static Stack <TileNode> Dijkstra(TileGraph tg, TileNode start, TileNode end)
        {
            frontier = new SimplePriorityQueue <TileNode, float>();
            frontier.Enqueue(start, 0f);
            node_dict = DijkstraInitialDictLoad(start, tg);
            List <TileNode> Expanded = new List <TileNode>();

            TileNode v;
            TileNode other;
            float    edge_weight;
            float    dist_to_node;
            float    cost_so_far;

            while (frontier.Count > 0)
            {
                v           = frontier.Dequeue();
                cost_so_far = node_dict[v].dist;
                Expanded.Add(v);

                //List<Edge> experiment = tg.getAdjacentEdges(v) as List<Edge>;
                foreach (Edge adj_edge in tg.getAdjacentEdges(v))
                {
                    other        = adj_edge.getNeighbor(v);
                    edge_weight  = adj_edge.weight;
                    dist_to_node = node_dict[other].dist;
                    if (cost_so_far + edge_weight < dist_to_node)
                    {
                        node_dict[other].dist   = cost_so_far + edge_weight;
                        node_dict[other].parent = v;
                    }

                    if (!Expanded.Any(node => node.isEqual(other)) && !frontier.Any(node => node.isEqual(other)))
                    {
                        frontier.Enqueue(other, node_dict[other].dist);
                    }
                }
            }

            Path = NodeDictToPath(node_dict, start, end);

            return(Path);
        }
Ejemplo n.º 12
0
        private static List <MessagePrioritiesModel> PriorityQueueToList(SimplePriorityQueue <string> senderQueue)
        {
            List <MessagePrioritiesModel> senderPriorities = new List <MessagePrioritiesModel>();

            while (senderQueue.Count != 0)
            {
                string first    = senderQueue.First;
                float  priority = senderQueue.GetPriority(first);
                MessagePrioritiesModel newMessagePriorities = new MessagePrioritiesModel()
                {
                    categoryName     = first,
                    categoryPriority = priority
                };
                senderPriorities.Add(newMessagePriorities);

                senderQueue.Dequeue();
            }

            return(senderPriorities);
        }
Ejemplo n.º 13
0
    static void StartTurn()
    {
        if (units.Count > 0)
        {
            TacticsMove unitTurn = units.Dequeue();
            if (unitTurn.dead)
            {
                StartTurn();
            }
            else
            {
                unitTurn.BeginTurn();
            }
        }

        /*else
         * {
         *  turnKey.Dequeue();
         * }*/
    }
Ejemplo n.º 14
0
        /// <summary>
        ///     Start algorytmu
        /// </summary>
        public void Start()
        {
            SimplePriorityQueue <Node> queue = new SimplePriorityQueue <Node>();

            // Korzeń drzewa trafia na początek kolejki.
            Node root = new Node(matrix, new List <Tuple <int, int> >(), -1, 0, 0);

            MatrixReduction(root);
            queue.Enqueue(root, root.LowerBound);

            bool leafReached = false;

            while (queue.Count > 0 && !leafReached)
            {
                Node poppedNode = queue.Dequeue();

                if (poppedNode.Level == size - 1)
                {
                    // Doszliśmy do liścia => tworzymy połączenie z miastem startowym.
                    poppedNode.Path.Add(new Tuple <int, int>(poppedNode.ID, 0));
                    GeneratePath(poppedNode);
                    finalDistance = poppedNode.LowerBound;
                    leafReached   = true;
                }
                else
                {
                    // Przetwarzamy każde dziecko danego węzła.
                    for (int i = 0; i < poppedNode.Matrix.GetLength(0); i++)
                    {
                        if (poppedNode.Matrix[poppedNode.ID, i] != int.MaxValue)
                        {
                            Node child = new Node(poppedNode.Matrix, poppedNode.Path, poppedNode.ID, i,
                                                  poppedNode.Level + 1);
                            MatrixReduction(child);
                            child.LowerBound += poppedNode.LowerBound + poppedNode.Matrix[poppedNode.ID, i];
                            queue.Enqueue(child, child.LowerBound);
                        }
                    }
                }
            }
        }
    public override List <int> findPath(int start, int goal)
    {
        SimplePriorityQueue <int> frontier    = new SimplePriorityQueue <int>();
        Dictionary <int, int>     visitedFrom = new Dictionary <int, int>();
        Dictionary <int, int>     costSoFar   = new Dictionary <int, int>();

        frontier.Enqueue(start, 0);
        visitedFrom[start] = -1;
        costSoFar[start]   = 0;
        while (frontier.Count > 0)
        {
            int current = frontier.Dequeue();
            if (current == goal)
            {
                break;
            }
            List <int> neighbours = navGraph.neighbours(current);
            foreach (int next in neighbours)
            {
                int nextCost = costSoFar[current];

                if (!costSoFar.ContainsKey(next) || nextCost < costSoFar[next])
                {
                    frontier.Enqueue(next, nextCost + guessCost(next, goal));
                    visitedFrom[next] = current;
                    costSoFar[next]   = nextCost;
                }
            }
        }
        List <int> path = new List <int>();
        int        nxt  = goal;

        while (nxt != start)
        {
            path.Insert(0, nxt);
            nxt = visitedFrom[nxt];
        }

        //Debug.Log ("giuydskijhdsakjh");
        return(path);
    }
Ejemplo n.º 16
0
        public static Tuple <Point, Queue <RobotAction> > RouteToClosestCell(Point start, HashSet <Point> targets, Map map)
        {
            var dist = new Dictionary <Point, int>();
            var prev = new Dictionary <Point, Point>();
            var Q    = new SimplePriorityQueue <Point, int>();

            dist[start] = 0;
            Q.Enqueue(start, 0);

            while (Q.Count > 0)
            {
                var u = Q.Dequeue();

                if (targets.Contains(u))
                {
                    return(GetActions(start, u, prev));
                }

                var alt = dist[u] + 1;

                foreach (var v in map.Neighbors(u))
                {
                    if (!dist.ContainsKey(v) || alt < dist[v])
                    {
                        dist[v] = alt;
                        prev[v] = u;
                        if (Q.Contains(v))
                        {
                            Q.UpdatePriority(v, alt);
                        }
                        else
                        {
                            Q.Enqueue(v, alt);
                        }
                    }
                }
            }
            ;

            return(null);
        }
Ejemplo n.º 17
0
    public Carryer SpawnGiverToGenerator(ItemOrder io)
    {
        List <Node> entrances = GetAdjRoadTiles();

        if (entrances.Count == 0)
        {
            return(null);
        }
        Node start = entrances[0];

        SimplePriorityQueue <Generator> queue = FindGeneratorToAccept(io);

        for (int i = 0; queue.Count > 0 && i < 5 && !ActiveSmartWalker; i++)
        {
            Structure   strg  = queue.Dequeue();
            List <Node> exits = strg.GetAdjRoadTiles();
            if (exits.Count == 0)
            {
                continue;
            }

            Queue <Node> path = pathfinder.FindPath(start, exits, "GiverCart");
            if (path.Count == 0)
            {
                continue;
            }

            GameObject go = world.SpawnObject("Walkers", "GiverCart", start);

            Carryer c = go.GetComponent <Carryer>();
            c.world       = world;
            c.Order       = io;
            c.Origin      = this;
            c.Destination = strg;
            c.Activate();
            c.SetPath(path);
            return(c);
        }

        return(null);
    }
Ejemplo n.º 18
0
    /// <summary>
    /// Performs whatever actions in the queue it can.
    /// </summary>
    public void performActions(Ecosystem eco)
    {
        // the queue for the next turn
        SimplePriorityQueue <Action> nextQueue = new SimplePriorityQueue <Action>();

        while (actionQueue.Count > 0)
        {
            Action nextAction = actionQueue.Dequeue();

            // if action is not possible, then ignore it (don't add it to the queue)
            if (nextAction.isPossible(this))
            {
                // ignore actions that the creature doesn't have enough resources to perform
                if (nextAction.enoughResources(this))
                {
                    // if there is time left for an action, perform it
                    if (nextAction.timeCost <= remainingTurnTime)
                    {
                        //Debug.Log("performing " + nextAction.name);
                        nextAction.performWrapper(this, eco);
                    }
                    else
                    {
                        // put actions that take too long on the next turn's queue
                        nextQueue.Enqueue(nextAction, nextAction.priority);
                    }
                }
            }
        }
        // actionQueue is now the queue for next turn
        actionQueue = nextQueue;

        // keep action queue a manageable size by clearing it every few steps, and clearing it if its size gets too big
        if (actionClearCount > actionClearInterval || actionQueue.Count >= actionClearSize)
        {
            actionClearCount = 0;
            actionQueue.Clear();
        }
        actionClearCount++;
        //Debug.Log("Queue size: " + actionQueue.Count);
    }
Ejemplo n.º 19
0
    /// <summary>
    /// A generic A* algorithm implemented using Priority Queues
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="startTile"></param>
    /// <param name="endTile"></param>
    /// <param name="IsValidNeighbour"></param>
    /// <param name="Heuristic"></param>
    /// <returns></returns>
    public static Dictionary <T, Cost <T> > FindPath <T>(T startTile, T endTile,
                                                         Func <T, bool> IsInvalidNeighbour, Func <T, T, float> Heuristic, bool flag)
        where T : class, IWieghtedNode <T>
    {
        SimplePriorityQueue <T, float> frontier = new SimplePriorityQueue <T, float>();

        frontier.Enqueue(startTile, 0);
        Dictionary <T, Cost <T> > comeFrom = new Dictionary <T, Cost <T> >();

        comeFrom[startTile] = new Cost <T>(null, 0);

        while (frontier.Count != 0)
        {
            T current = frontier.Dequeue();
            if (current == endTile)
            {
                break;
            }
            Debug.Log(current);
            foreach (T next in current.GetNeighboursList(flag))
            {
                // Ignore impassable tiles
                if (IsInvalidNeighbour(next))
                {
                    continue;
                }

                float newCost = comeFrom[current].cost + next.WalkingCost(current); // cost in graph
                if (!comeFrom.ContainsKey(next) || newCost < comeFrom[next].cost)
                {
                    // Heuristic to find cost to arrive to end
                    float priority = newCost + Heuristic(next, endTile);
                    frontier.Enqueue(next, priority);
                    comeFrom[next] = new Cost <T>(current, newCost);
                }
            }
        }

        return(comeFrom);
    }
Ejemplo n.º 20
0
            public void Kruskal()
            {
                SimplePriorityQueue <Edge> pq = new SimplePriorityQueue <Edge>();

                //add all the edges to priority queue,
                //sort the edges on weights
                for (int i = 0; i < allEdges.Count; i++)
                {
                    pq.Enqueue(allEdges[i], allEdges[i].weight);
                }
                //create a parent []
                int[] parent = new int[vertices];
                //MakeSet
                MakeSet(parent);
                List <Edge> mst   = new List <Edge>();
                int         index = 0;

                //process vertices - 1 edges
                while (index < vertices - 1)
                {
                    Edge edge = pq.Dequeue();
                    //check if adding this edge creates a cycle
                    int x_set = Find(parent, edge.source);
                    int y_set = Find(parent, edge.destination);
                    if (x_set == y_set)
                    {
                        //ignore, will create cycle
                    }
                    else
                    {
                        //add it to our final result
                        mst.Add(edge);
                        index++;
                        Unite(parent, x_set, y_set);
                    }
                }
                //print MST
                Console.WriteLine("Minimum Spanning Tree: ");
                PrintGraph(mst);
            }
Ejemplo n.º 21
0
        public double Prim(long pointCount, long[][] points)
        {
            double path = 0;

            double[] cost = new double[pointCount];
            SimplePriorityQueue <long, double> priorityQ = new SimplePriorityQueue <long, double>();

            for (int I = 0; I < pointCount; I++)
            {
                cost[I] = int.MaxValue;
                priorityQ.Enqueue(I, int.MaxValue);
            }
            cost[0] = 0;
            long v = 0;

            priorityQ.UpdatePriority(0, 0);
            while (priorityQ.Count != 0)
            {
                v = priorityQ.Dequeue();
                if (cost[v] > path)
                {
                    path = cost[v];
                }
                for (int i = 0; i < pointCount; i++)
                {
                    if (i == v || !priorityQ.Contains(i))
                    {
                        continue;
                    }
                    double dist = RealDist(points[v][0], points[v][1], points[i][0], points[i][1]);
                    if (cost[i] > dist)
                    {
                        priorityQ.UpdatePriority(i, dist);
                        cost[i] = dist;
                    }
                }
            }

            return(path);
        }
Ejemplo n.º 22
0
    private IEnumerator Active()
    {
        while (priority_queue.Count != 0)
        {
            Dictionary <Node, float> dic = priority_queue.First;

            foreach (var v in dic)
            {
                current  = Convert.ToInt32(v.Key.name);
                distance = -v.Value;
                break;
            }

            priority_queue.Dequeue();

            if (d[current] < distance)
            {
                continue;
            }

            foreach (var v in graph.nodeList[current].nodeDic)
            {
                heuristic = Vector3.Distance(GameObject.Find(v.Key.name.ToString()).transform.position, endNode.transform.position);

                int next = Convert.ToInt32(v.Key.name);

                float nextDistance = distance + v.Value + heuristic;

                if (nextDistance < d[next])
                {
                    d[next] = nextDistance + heuristic;
                    priority_queue.Enqueue(Make_pair(graph.nodeList[next], -nextDistance), -nextDistance);
                    p[next] = current;
                }
            }
            yield return(null);
        }

        StartCoroutine(DrawPath());
    }
Ejemplo n.º 23
0
        public List <Tile> FindPath(Tile start, Tile goal)
        {
            var cameFrom  = new Dictionary <Tile, Tile>();
            var costSoFar = new Dictionary <Tile, int>();

            cameFrom[start]  = null;
            costSoFar[start] = 0;

            var frontier = new SimplePriorityQueue <Tile>();

            frontier.Enqueue(start, 0);

            while (frontier.Count > 0)
            {
                var current = frontier.Dequeue();

                if (current.IsEqualTo(goal))
                {
                    break;
                }

                foreach (var tile in current.Neighbors)
                {
                    var next    = tile.GetComponent <Tile>();
                    var newCost = costSoFar[current] + next.Cost;

                    if (costSoFar.ContainsKey(next) && newCost >= costSoFar[next])
                    {
                        continue;
                    }

                    costSoFar[next] = newCost;
                    var priority = newCost + Heuristic(goal, next) * next.Cost;
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }

            return(GetPath(cameFrom, goal));
        }
Ejemplo n.º 24
0
        public async void Perform()
        {
            Console.WriteLine("\tStarted A*-based solver.");

            // add root as a first element (frontier)
            openSetexp.Enqueue(PlainBoard.GetBulbsLayer(), 0);

            while (openSetexp.Count > 0)
            {
                var currentBulbLayer = openSetexp.Dequeue();

                var currentBoard = new Board(PlainBoard);
                currentBoard.PutBulbsLayer(currentBulbLayer);

                if (currentBoard.ValidateSolution())
                {
                    currentBoard.Visits = this.Visits;
                    solutions.Add(currentBoard);
                    break;
                }

                Visits += 1;
                var successors = currentBoard.GetSuccessors();

                foreach (var successorBulbLayer in successors)
                {
                    var successorBoard = new Board(PlainBoard);
                    successorBoard.PutBulbsLayer(successorBulbLayer);

                    openSetexp.Enqueue(successorBulbLayer, (float)(successorBoard.GetProfit() + 0.01 * successorBoard.GetNumberOfLitFields()));
                }
            }

            foreach (var board in solutions)
            {
                Console.WriteLine("A* solution: ", Color.Orchid);
                Console.WriteLine("Visits:" + board.Visits, Color.Orchid);
                board.Draw();
            }
        }
Ejemplo n.º 25
0
 public void UCSearch(int v, int g, bool[] visited, ref int[] parent)
 {
     SimplePriorityQueue<int, int> open = new SimplePriorityQueue<int, int>(); // Orders elements in an ascending order by weight.
     int[] cost = new int[size]; // Stores the least cost for all nodes starting with the start node until the goal node.
     for (int i = 0; i < size; i++)
     {
         cost[i] = 0;
     }
     open.Enqueue(v, 0);
     while (open.Count > 0)
     {
         int x = open.Dequeue();
         visited[x] = true; // We mark the visited node here since UCS only expands the node with the least cost
         if (x == g)
         {
             return;
         }
         for (int i = 0; i < adj[x].Count; i++)
         {
             if (!open.Contains(adj[x][i]) && !visited[adj[x][i]]) // Adding nodes with their costs too the Queue
             {
                 parent[adj[x][i]] = x;
                 cost[adj[x][i]] = cost[x] + weight[x][i];
                 open.Enqueue(adj[x][i], cost[adj[x][i]]);
             }
             else if (open.Contains(adj[x][i])) // Updates the cost of a node in case a new path is found
             {
                 int temp = cost[adj[x][i]];
                 cost[adj[x][i]] = Math.Min(cost[adj[x][i]], (cost[x] + weight[x][i]));
                 if (cost[adj[x][i]] < temp) // If the new path has a smaller cost, then update the node and push it back to Queue
                 {
                     parent[adj[x][i]] = x; // Update the parent in case a less-cost path is found.
                     open.Remove(adj[x][i]);
                     open.Enqueue(adj[x][i], cost[adj[x][i]]);
                 }
             }
         }
     } // End of while
 } // End of UCSearch function
Ejemplo n.º 26
0
    void GenerateHoles(int amount)
    {
        SimplePriorityQueue <KeyValuePair <Vector3Int, int>, int> holesData = new SimplePriorityQueue <KeyValuePair <Vector3Int, int>, int>();

        for (int i = 0; i < amount; i++)
        {
            Vector3Int center = new Vector3Int(prng.Next(0, voxelMap.Width),
                                               prng.Next(0, voxelMap.Height),
                                               prng.Next(i * voxelMap.Depth / amount, (i + 1) * voxelMap.Depth / amount));
            int size = prng.Next(8000, 16000);
            holesData.Enqueue(new KeyValuePair <Vector3Int, int>(center, size), center.z);
        }

        // TODO: parallelyze work here (and take care of thread safety of voxelMap)

        while (holesData.Count > 0)
        {
            KeyValuePair <Vector3Int, int> data = holesData.Dequeue();
            Debug.Log("Generating cave at " + data.Key);
            GenerateIrregularCaveInMap(data.Key, data.Value);
        }
    }
Ejemplo n.º 27
0
Archivo: World.cs Proyecto: bmjoy/osuve
    private void RenderThread()
    {
        while (_loadQueue.Count > 0)
        {
            Chunk newChunkScript = _loadQueue.Dequeue();

            if (newChunkScript != null)
            {
                Debug.Log("Rendering next chunk");
                try
                {
                    newChunkScript.GenerateBlocks();
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
        }

        _rendering = false;
    }
Ejemplo n.º 28
0
        void UCSearch(City root, City destiny, List <City> cities)
        {
            SimplePriorityQueue <City> Frontier = new SimplePriorityQueue <City>();

            root.PathCost = 0;
            Frontier.Enqueue(root, 0);
            float sum;

            while (Frontier.Count != 0)
            {
                sum = Frontier.GetPriority(Frontier.First);
                City parent = (City)Frontier.Dequeue();
                tbResult.Text += ("\n Expando el nodo de: " + parent.CityName + " Llevando un costo actual de: " + sum);
                tbOrder.Text  += ("\n" + parent.CityName + " Costo: " + sum + "\n ↓");
                if (parent == destiny)
                {
                    tbResult.Text += ("\n Llegue al destino con un costo total de: " + sum);
                    break;
                }
                cities.Add(parent);
                foreach (var tempRute in parent.Rutes)
                {
                    if (!cities.Contains(tempRute.DestinationCity))
                    {
                        if (!Frontier.Contains(tempRute.DestinationCity))
                        {
                            Frontier.Enqueue(tempRute.DestinationCity, sum + tempRute.Cost);
                        }
                        else
                        {
                            if (Frontier.GetPriority(tempRute.DestinationCity) > sum + tempRute.Cost)
                            {
                                Frontier.TryUpdatePriority(tempRute.DestinationCity, sum + tempRute.Cost);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 29
0
        public WeightedGraph SpanningTree()
        {
            var tree      = new WeightedGraph();
            var edges     = new SimplePriorityQueue <Edge, int>();
            var startNode = _nodes.Values.First();

            //C : min,B
            foreach (var edge in startNode.GetEdges())
            {
                edges.Enqueue(edge, edge.GetWeight());
            }
            //A
            tree.AddNode(startNode.GetLabel());

            while (tree.GetCountNode() < GetCountNode())
            {
                //C
                var minEdge = edges.Dequeue();
                if (tree.ContainsNode(minEdge.To()))
                {
                    continue;
                }
                //C
                tree.AddNode(minEdge.To());
                //A->C
                tree.AddEdge(minEdge.From(), minEdge.To(), minEdge.GetWeight());
                //C
                var nextNode = Get(minEdge.To());

                foreach (var edge in nextNode.GetEdges())
                {
                    if (!tree.ContainsNode(edge.To()))
                    {
                        edges.Enqueue(edge, edge.GetWeight());
                    }
                }
            }
            return(tree);
        }
Ejemplo n.º 30
0
    private void RenderThread()
    {
        while (_loadQueue.Count > 0)
        {
            Chunk newChunkScript = _loadQueue.Dequeue();

            if (newChunkScript != null)
            {
                // Errors in threads need to be manually caught and sent to the main thread
                try
                {
                    newChunkScript.GenerateBlocks();
                }
                catch (Exception ex)
                {
                    Debug.LogException(ex);
                }
            }
        }

        _rendering = false;
    }
Ejemplo n.º 31
0
        public Dictionary <int, int> MainAlgorithm(int source)
        {
            SimplePriorityQueue <int> priorityQueue = new SimplePriorityQueue <int>();

            InitiateLenghts(source);
            priorityQueue.Enqueue(source, 0);
            while (priorityQueue.Any())
            {
                int operatedVertex = priorityQueue.First();
                priorityQueue.Dequeue();
                foreach (var item in calculatedGraph.vertices[operatedVertex].outgoingEdges)
                {
                    int newLenght = lenghts[operatedVertex] + item.Value;
                    if (lenghts[item.Key] > newLenght)
                    {
                        lenghts[item.Key] = newLenght;
                        priorityQueue.Enqueue(item.Key, newLenght);
                    }
                }
            }
            return(lenghts);
        }
Ejemplo n.º 32
0
        public AStarSearch(WorldMap worldMap, Tile <TileData> start, Tile <TileData> goal, NeighborFunction getNeighbors)
        {
            SimplePriorityQueue <Tile <TileData>, float> frontier = new SimplePriorityQueue <Tile <TileData>, float>();

            frontier.Enqueue(start, 0f);

            cameFrom[start]  = start;
            costSoFar[start] = 0;



            while (frontier.Count > 0)
            {
                Tile <TileData> current = frontier.Dequeue();

                if (current == goal)
                {
                    reachedDestination = true;
                    break;
                }

                foreach (Tile <TileData> next in getNeighbors(worldMap, current))
                {
                    float newCost = costSoFar[current] + worldMap.GetCost(current, next);

                    if (costSoFar.ContainsKey(next) && !(newCost < costSoFar[next]))
                    {
                        continue;
                    }

                    costSoFar[next] = newCost;
                    float priority = newCost + Heuristic(next, goal);
                    frontier.Enqueue(next, priority);
                    cameFrom[next] = current;
                }
            }

            Debug.Log("Destination Unreached");
        }
Ejemplo n.º 33
0
        // TODO: use a population map to guide randomness
        private IEnumerable <Road> CreateRoads()
        {
            // Algorithm from http://nothings.org/gamedev/l_systems.html
            var potentialRoads = new SimplePriorityQueue <Road>();
            var acceptedRoads  = new List <Road>();

            var StartX = Rand.Next(20, EngineConsts.MAP_WIDTH - 20);
            var StartY = Rand.Next(20, EngineConsts.MAP_HEIGHT - 20);
            var Length = Rand.NextDouble() * 15 + 10;
            var Angle  = Math.PI / 2 * Rand.Next(0, 4);
            var r1     = new Road(0, StartX, StartY, Length, Angle, 5, 0, 0);
            var r2     = new Road(0, StartX, StartY, Length, Angle + Math.PI, 5, 0, 0);

            potentialRoads.Enqueue(r1, 0);
            potentialRoads.Enqueue(r2, 0);

            while (potentialRoads.Count > 0)
            {
                Road  road = potentialRoads.First;
                float prio = potentialRoads.GetPriority(road);
                potentialRoads.Dequeue();

                if (CheckLocalConstraints(road, acceptedRoads, out Road newRoad))
                {
                    acceptedRoads.Add(newRoad);
                    ProjectRoadToMap(newRoad);

                    foreach (Road rq in SolveGlobalGoals(newRoad))
                    {
                        if (rq != null)
                        {
                            potentialRoads.Enqueue(rq, prio + 1);
                        }
                    }
                }
            }

            return(acceptedRoads);
        }
Ejemplo n.º 34
0
        public void LoadChunks(int n, bool async = true)
        {
            int s = chunkLoadingList.Count;

            for (int i = 0; i < Math.Min(n - s, chunkLoadQueue.Count); i++)
            {
                ChunkIndex ci = chunkLoadQueue.Dequeue();
                if (Chunks.ContainsKey(ci))
                {
                    i--;
                }
                else
                {
                    if (world.Player.ChunkID.Distance(world.Size, ci) < World.LoadDistance)
                    {
                        Chunk c = chunkPool.GetObject();
                        c.ChunkID = ci;

                        chunkLoadingList.Add(ci);

                        if (async)
                        {
                            Task t = Task.Factory.StartNew(() =>
                            {
                                LoadChunk(ci, c);
                            });
                        }
                        else
                        {
                            LoadChunk(ci, c);
                        }
                    }
                    else
                    {
                        i--;
                    }
                }
            }
        }
Ejemplo n.º 35
0
        /// <summary>
        /// Generar y retornar el árbol SPF de la topología en un proyecto, tomando el parámetro como punto de origen
        /// </summary>
        /// <param name="idRouterOrigen"></param>
        /// <param name="idProyecto"></param>
        /// <param name="minBW"></param>
        /// <returns></returns>
        public static List<NodoDijkstra> GenerarRutas(NodoDijkstra idRouterOrigen, int idProyecto, double minBW, int nTipoMetrica = 2, int idAfinidad = 0)
        {
            idRouterOrigen.nMinDistancia = 0.0;
            SimplePriorityQueue<NodoDijkstra> routerQueue = new SimplePriorityQueue<NodoDijkstra>();
            routerQueue.Enqueue(idRouterOrigen, 1);

            //mantiene el registro de todos los nodos de la topologia por el que se pasa
            List<NodoDijkstra> routerList = new List<NodoDijkstra>();
            routerList.Add(idRouterOrigen);

            while (routerQueue.Count > 0)
            {
                NodoDijkstra currentRouter = routerQueue.Dequeue();
                //Visita cada enlace adyacente al router u
                foreach (var enlace in currentRouter.listaEnlacesDijkstra)
                {
                    int idRouterVecino = 0;
                    //Fix: Asegurandose de que se use el id del router adyacente en el enlace
                    if (enlace.idRouterB != currentRouter.idRouter)
                    {
                        idRouterVecino = enlace.idRouterB;
                        //enlace.target = enlace.targetB;
                    }
                    else
                    {
                        idRouterVecino = enlace.idRouterA;
                        //enlace.target = enlace.targetA;
                    }
                    //NodoDijkstra vecino = new NodoDijkstra(idRouterVecino, idProyecto);

                    NodoDijkstra vecino = enlace.target;

                    double nPesoBandwidth = 0;
                    switch(nTipoMetrica)        //ignore var name, aqui va lo del tipo de peso
                    {
                        case 1: //Pesos Administrativos
                            nPesoBandwidth = enlace.nPesoAdministrativo;
                            break;
                        case 2: //Minima Cantidad de Saltos
                            nPesoBandwidth = 1;
                            break;
                        case 3: // 1/BW Reservado
                            nPesoBandwidth = 1.00 / (enlace.nBandwidth - enlace.nBandwidthDisponible);
                            break;
                        case 4: // 1/BW Disponible
                            nPesoBandwidth = 1.00 / enlace.nBandwidthDisponible;
                            break;
                        default:
                            nPesoBandwidth = 1;
                            break;
                    }

                    double nDistanciaTotal = currentRouter.nMinDistancia + nPesoBandwidth;

                    //Aqui ocurre el filtro por afinidad
                    if (idAfinidad == 0)    //No afinidad definida
                    {
                        //En este if ocurre el filtro por BW disponible
                        if (nDistanciaTotal < vecino.nMinDistancia && minBW < enlace.nBandwidth) //Constraint check
                        {
                            if (routerQueue.Contains(vecino))
                                routerQueue.Remove(vecino);
                            vecino.nMinDistancia = nDistanciaTotal;
                            vecino.idRouterPrevio = currentRouter;
                            enlace.nBandwidthDisponible -= minBW; //reservar el BW en el enlace

                            routerQueue.Enqueue(vecino, 1);
                        }
                    }
                    else  //Afinidad definida
                    {
                        if (idAfinidad == enlace.idAfinidad)    //Afinidad check
                        {
                            //En este if ocurre el filtro por BW disponible
                            if (nDistanciaTotal < vecino.nMinDistancia && minBW < enlace.nBandwidth) //Constraint check
                            {
                                if (routerQueue.Contains(vecino))
                                    routerQueue.Remove(vecino);
                                vecino.nMinDistancia = nDistanciaTotal;
                                vecino.idRouterPrevio = currentRouter;
                                enlace.nBandwidthDisponible -= minBW; //reservar el BW en el enlace

                                routerQueue.Enqueue(vecino, 1);
                            }
                        }
                    }

                    //Agrega el router (bueno, los 2) al registro
                    int indexTarget = routerList.FindIndex(n => n.idRouter == vecino.idRouter);
                    if (indexTarget != -1)
                        routerList[indexTarget] = vecino;
                    else
                        routerList.Add(vecino);
                    int indexSource = routerList.FindIndex(n => n.idRouter == currentRouter.idRouter);
                    if (indexSource != -1)
                        routerList[indexSource] = currentRouter;
                    else
                        routerList.Add(currentRouter);

                }
            }
            return routerList;
        }
Ejemplo n.º 36
0
    public Path_AStar(World world, Tile tileStart, Tile tileEnd)
    {
        // Check to see if we have a valid tile graph
        if(world.tileGraph == null) {
            world.tileGraph = new Path_TileGraph(world);
        }

        // A dictionary of all valid, walkable nodes.
        Dictionary<Tile, Path_Node<Tile>> nodes = world.tileGraph.nodes;

        // Make sure our start/end tiles are in the list of nodes!
        if(nodes.ContainsKey(tileStart) == false) {
            Debug.LogError("Path_AStar: The starting tile isn't in the list of nodes!");

            return;
        }
        if(nodes.ContainsKey(tileEnd) == false) {
            Debug.LogError("Path_AStar: The ending tile isn't in the list of nodes!");
            return;
        }

        Path_Node<Tile> start = nodes[tileStart];
        Path_Node<Tile> goal = nodes[tileEnd];

        // Mostly following this pseusocode:
        // https://en.wikipedia.org/wiki/A*_search_algorithm

        List<Path_Node<Tile>> ClosedSet = new List<Path_Node<Tile>>();

        /*		List<Path_Node<Tile>> OpenSet = new List<Path_Node<Tile>>();
        OpenSet.Add( start );
        */

        SimplePriorityQueue<Path_Node<Tile>> OpenSet = new SimplePriorityQueue<Path_Node<Tile>>();
        OpenSet.Enqueue( start, 0);

        Dictionary<Path_Node<Tile>, Path_Node<Tile>> Came_From = new Dictionary<Path_Node<Tile>, Path_Node<Tile>>();

        Dictionary<Path_Node<Tile>, float> g_score = new Dictionary<Path_Node<Tile>, float>();
        foreach(Path_Node<Tile> n in nodes.Values) {
            g_score[n] = Mathf.Infinity;
        }
        g_score[ start ] = 0;

        Dictionary<Path_Node<Tile>, float> f_score = new Dictionary<Path_Node<Tile>, float>();
        foreach(Path_Node<Tile> n in nodes.Values) {
            f_score[n] = Mathf.Infinity;
        }
        f_score[ start ] = heuristic_cost_estimate( start, goal );

        while( OpenSet.Count > 0 ) {
            Path_Node<Tile> current = OpenSet.Dequeue();

            if(current == goal) {
                // We have reached our goal!
                // Let's convert this into an actual sequene of
                // tiles to walk on, then end this constructor function!
                reconstruct_path(Came_From, current);
                return;
            }

            ClosedSet.Add(current);

            foreach(Path_Edge<Tile> edge_neighbor in current.edges) {
                Path_Node<Tile> neighbor = edge_neighbor.node;

                if( ClosedSet.Contains(neighbor) == true )
                    continue; // ignore this already completed neighbor

                float movement_cost_to_neighbor = neighbor.data.movementCost * dist_between(current, neighbor);

                float tentative_g_score = g_score[current] + movement_cost_to_neighbor;

                if(OpenSet.Contains(neighbor) && tentative_g_score >= g_score[neighbor])
                    continue;

                Came_From[neighbor] = current;
                g_score[neighbor] = tentative_g_score;
                f_score[neighbor] = g_score[neighbor] + heuristic_cost_estimate(neighbor, goal);

                if(OpenSet.Contains(neighbor) == false) {
                    OpenSet.Enqueue(neighbor, f_score[neighbor]);
                }

            } // foreach neighbour
        } // while

        // If we reached here, it means that we've burned through the entire
        // OpenSet without ever reaching a point where current == goal.
        // This happens when there is no path from start to goal
        // (so there's a wall or missing floor or something).

        // We don't have a failure state, maybe? It's just that the
        // path list will be null.
    }
Ejemplo n.º 37
0
        /// <summary>
        /// Finds a path through the puzzle originating from startNode and ending at endNode, going across from left to right.
        /// Based on A* pathfinding algorithm, it theoretically is supposed to find the shortest possible path, but this is thus far untested/unproven.
        /// 
        /// First uses buildGraph to determine all possible and relevant edges between each tile/node, then uses a mostly standard A* algorithm, until
        /// an orange tile is encountered and the rules change (because of "scents"). Every time an orange tile is encountered, a nested A*-based loop (referred to as the "orange loop")
        /// is ran (but with orange-scented rules) which essentially starts at the orange tile and seeks any tile that will remove the orange scent, or the endNode.
        /// Every tile encountered that exits the orange loop is added to the main open set (the open set of the normal A* loop) with their cost to get there through the orange loop.
        /// 
        /// </summary>
        /// <returns>Returns a list of all possible paths to the endNode, and the shortest one, or the one with the least tree height, is to be considered the answer</returns>
        public List<PathTreeNode> solve()
        {
            resetGraphEdges();
            buildGraph();

            //A*-based pathfinding algorithm
            List<Node> closedSet = new List<Node>();
            SimplePriorityQueue<Node> openSet = new SimplePriorityQueue<Node>();
            List<Node> closedOrangeSet = new List<Node>();
            SimplePriorityQueue<Node> openOrangeSet;
            List<PathTreeNode> Leaves = new List<PathTreeNode>();

            if(startNode.edges.Count == 0)
            {
                return Leaves;
            }

            startNode.g = 0;
            openSet.Enqueue(startNode, 0);
            PathTreeNode root = new PathTreeNode(startNode.row, -1);
            Leaves.Add(root);
            

            while (openSet.Count > 0)
            {
                Node current = openSet.Dequeue();
                PathTreeNode currentStep = null;

                Predicate<PathTreeNode> matchingCurrentPos = aStep => aStep.row == currentStep.row && aStep.col == currentStep.col;

                if (current == endNode)
                {
                    return Leaves;
                }

                if(current.edges.Count == 0)
                {
                    continue;
                }

                foreach (PathTreeNode leaf in Leaves)
                {
                    if(leaf.row == current.row && leaf.col == current.col)
                    {
                        if(currentStep == null || currentStep.height > leaf.height)
                        {
                            currentStep = leaf;
                        }
                    }
                }
                if (currentStep != null)
                {
                    Leaves.RemoveAll(matchingCurrentPos);
                }

                if(current.color == 1)
                {
                    openOrangeSet = new SimplePriorityQueue<Node>();
                    openOrangeSet.Enqueue(current, current.f);
                    currentStep.isOrangeStep = true;
                    Leaves.Add(currentStep);

                    while(openOrangeSet.Count > 0)
                    {
                        Node currentOrange = openOrangeSet.Dequeue();
                        PathTreeNode currentOrangeStep = null;
                        Predicate<PathTreeNode> matchingCurrentOrangePos = aStep => aStep.isOrangeStep && aStep.row == currentOrangeStep.row && aStep.col == currentOrangeStep.col;

                        if (currentOrange.edges.Count == 0)
                        {
                            continue;
                        }

                        foreach (PathTreeNode leaf in Leaves)
                        {
                            if (leaf.isOrangeStep && leaf.row == currentOrange.row && leaf.col == currentOrange.col)
                            {
                                if (currentOrangeStep == null || currentOrangeStep.height > leaf.height)
                                {
                                    currentOrangeStep = leaf;
                                }
                            }
                        }
                        if (currentOrangeStep != null)
                        {
                            Leaves.RemoveAll(matchingCurrentOrangePos);
                        }

                        closedOrangeSet.Add(currentOrange);
                        foreach (Edge toOrangeNeighbor in currentOrange.edges)
                        {
                            if (closedSet.Contains(toOrangeNeighbor.childNode) || closedOrangeSet.Contains(toOrangeNeighbor.childNode))
                            {
                                continue;
                            }
                            if (toOrangeNeighbor.childNode.col == cols)
                            {
                                toOrangeNeighbor.childNode.row = currentOrange.row;
                            }

                            int currentOrangeG = currentOrange.g + Math.Abs((toOrangeNeighbor.childNode.row - currentOrange.row) + (toOrangeNeighbor.childNode.col - currentOrange.col)) + toOrangeNeighbor.childNode.weight;

                            if (openSet.Contains(toOrangeNeighbor.childNode) && toOrangeNeighbor.childNode.g < currentOrangeG)
                            {
                                continue;
                            }

                            PathTreeNode aNextStep;

                            if ((toOrangeNeighbor.isScented && !toOrangeNeighbor.isOrangeScented) || toOrangeNeighbor.childNode == endNode)
                            {
                                toOrangeNeighbor.childNode.f = currentOrangeG + heuristic(toOrangeNeighbor.childNode.col);
                                toOrangeNeighbor.childNode.g = currentOrangeG;
                                openSet.Enqueue(toOrangeNeighbor.childNode, toOrangeNeighbor.childNode.f);
                                aNextStep = new PathTreeNode(toOrangeNeighbor.childNode.row, toOrangeNeighbor.childNode.col, currentOrangeStep);
                                Leaves.Add(aNextStep);
                                continue;
                            }
                            if(toOrangeNeighbor.childNode.color == 4)
                            {
                                continue;
                            }
                            if (!openOrangeSet.Contains(toOrangeNeighbor.childNode))
                            {
                                toOrangeNeighbor.childNode.f = currentOrangeG + heuristic(toOrangeNeighbor.childNode.col);
                                openOrangeSet.Enqueue(toOrangeNeighbor.childNode, toOrangeNeighbor.childNode.f);
                            }
                            else if (currentOrangeG >= toOrangeNeighbor.childNode.g)
                            {
                                continue;
                            }

                            toOrangeNeighbor.childNode.g = currentOrangeG;
                            toOrangeNeighbor.childNode.f = currentOrangeG + heuristic(toOrangeNeighbor.childNode.col);
                            openOrangeSet.UpdatePriority(toOrangeNeighbor.childNode, toOrangeNeighbor.childNode.f);
                            aNextStep = new PathTreeNode(toOrangeNeighbor.childNode.row, toOrangeNeighbor.childNode.col, currentOrangeStep, true);
                            Leaves.Add(aNextStep);
                        }
                    }
                    Predicate<PathTreeNode> isOrangeStepLeaf = aStep => aStep.isOrangeStep;
                    Leaves.RemoveAll(isOrangeStepLeaf);

                    closedSet.Add(current);
                }
                else
                {
                    closedSet.Add(current);
                    foreach (Edge toNeighbor in current.edges)
                    {
                        if (closedSet.Contains(toNeighbor.childNode))
                        {
                            continue;
                        }
                        if(current.col == -1)
                        {
                            current.row = toNeighbor.childNode.row;
                        }
                        else if(toNeighbor.childNode.col == cols)
                        {
                            toNeighbor.childNode.row = current.row;
                        }

                        int currentG = current.g + Math.Abs((toNeighbor.childNode.row - current.row) + (toNeighbor.childNode.col - current.col)) + toNeighbor.childNode.weight;
                        PathTreeNode aNextStep;

                        if (!openSet.Contains(toNeighbor.childNode))
                        {
                            toNeighbor.childNode.f = currentG + heuristic(toNeighbor.childNode.col);
                            openSet.Enqueue(toNeighbor.childNode, toNeighbor.childNode.f);
                        }
                        else if (currentG >= toNeighbor.childNode.g)
                        {
                            continue;
                        }

                        toNeighbor.childNode.g = currentG;
                        toNeighbor.childNode.f = currentG + heuristic(toNeighbor.childNode.col);
                        openSet.UpdatePriority(toNeighbor.childNode, toNeighbor.childNode.f);
                        aNextStep = new PathTreeNode(toNeighbor.childNode.row, toNeighbor.childNode.col, currentStep);
                        Leaves.Add(aNextStep);
                    }
                }
            }

            return Leaves;
        }
Ejemplo n.º 38
0
		/// <summary>
		/// Performs an A* search following the Node Array A* implementation
		/// </summary>
		public Path FindPath(IMap map, int start, int target)
        {
			this.isGoal = nodeId => nodeId == target;
			this.calculateHeuristic = nodeId => map.GetHeuristic(nodeId, target);
			this.map = map;

			var heuristic = calculateHeuristic(start);

            var startNode = new AStarNode(start, 0, heuristic, CellStatus.Open);
			var openQueue = new SimplePriorityQueue<int>();
			openQueue.Enqueue(start, startNode.F);

			// The open list lookup is indexed by the number of nodes in the graph/map,
			// and it is useful to check quickly the status of any node that has been processed
			var nodeLookup = new AStarNode?[map.NrNodes];
			nodeLookup[start] = startNode;

            while (openQueue.Count != 0)
            {
                var nodeId = openQueue.Dequeue();
                var node = nodeLookup[nodeId].Value;
				
                if (isGoal(nodeId))
                {
                    return ReconstructPath(nodeId, nodeLookup);
                }

                ProcessNeighbours(nodeId, node, nodeLookup, openQueue);

				// Close the node. I hope some day the will implement something
				// like the records in F# with the "with" keyword
				nodeLookup[nodeId] = new AStarNode(node.Parent, node.G, node.H, CellStatus.Closed);
			}

			// No path found. We could return a null, but since I read the book "Code Complete" I decided
			// its best to return an empty path, and I'll return a -1 as PathCost
			// TODO: Additionally, all those magic numbers like this -1 should be converted to explicit,
			// clearer constants
	        return new Path(new List<int>(), -1);
        }