Exemple #1
0
        public static int[][] A_StarAlgorithm(int startRow, int startCol, int endRow, int endCol, int[][] graph)
        {
            List <List <Node> > nodes = initializeNodes(graph);
            Node startNode            = nodes[startRow][startCol];
            Node endNode = nodes[endRow][endCol];

            startNode.distanceFromStart      = 0;
            startNode.estimatedDistanceToEnd = calculateManhattanDistance(startNode, endNode);

            List <Node> nodesToVisitList = new List <Node>();

            nodesToVisitList.Add(startNode);

            MinHeap nodesToVisit = new MinHeap(nodesToVisitList);

            while (!nodesToVisit.isEmpty())
            {
                Node currentMinDistanceNode = nodesToVisit.Remove();
                if (currentMinDistanceNode == endNode)
                {
                    break;
                }

                List <Node> neighbors = getNeighboringNodes(currentMinDistanceNode, nodes);
                foreach (var neighbor in neighbors)
                {
                    if (neighbor.val == 1)
                    {
                        continue;
                    }

                    int tentativeDistanceToNeighbor = currentMinDistanceNode.distanceFromStart + 1;
                    if (tentativeDistanceToNeighbor >= neighbor.distanceFromStart)
                    {
                        continue;
                    }
                    neighbor.nodeCameFrom           = currentMinDistanceNode;
                    neighbor.distanceFromStart      = tentativeDistanceToNeighbor;
                    neighbor.estimatedDistanceToEnd = neighbor.distanceFromStart + calculateManhattanDistance(neighbor, endNode);

                    if (!nodesToVisit.ContainsNode(neighbor))
                    {
                        nodesToVisit.Insert(neighbor);
                    }
                    else
                    {
                        nodesToVisit.Update(neighbor);
                    }
                }
            }
            return(retrieveShortestPath(endNode));
        }