コード例 #1
0
ファイル: Astar.cs プロジェクト: dolow/taxi-manhattan
    public static List <int> Exec(int start, int goal, int[] map, int width, int height)
    {
        try
        {
            if (map[start] == 0 || map[goal] == 0)
            {
                return new List <int>()
                       {
                           start
                       }
            }
            ;
        }
        catch (Exception)
        {
            return(new List <int>()
            {
                start
            });
        }


        Dictionary <int, int> path = new Dictionary <int, int>();

        Dictionary <int, SearchNode> openedNode = new Dictionary <int, SearchNode>();
        Dictionary <int, int>        score      = new Dictionary <int, int>();
        SearchNode startNode = new SearchNode(0, start);

        openedNode.Add(start, startNode);

        while (openedNode.Keys.Count > 0)
        {
            SearchNode current = null;
            foreach (KeyValuePair <int, SearchNode> entry in openedNode)
            {
                SearchNode node = entry.Value;

                if (current == null || (node.score < current.score && !node.IsImpassible()))
                {
                    current = node;
                }
            }

            if (current.address == goal)
            {
                // TODO: overhead
                return(Astar.MakeRoute(path, start, goal));
            }

            openedNode.Remove(current.address);

            if (current.IsImpassible())
            {
                continue;
            }

            List <int> neighbors = Astar.Neighbors(current.address, map, width, height);
            for (int i = 0; i < neighbors.Count; i++)
            {
                int neighborAddress = neighbors[i];
                if (!score.ContainsKey(neighborAddress))
                {
                    // TODO: heuristic
                    if (map[neighborAddress] == Astar.Impassible)
                    {
                        score[neighborAddress] = SearchNode.ImpassibleScore;
                    }
                    else
                    {
                        score[neighborAddress] = current.score + 1;
                        path[neighborAddress]  = current.address;
                    }
                    SearchNode neighborNode = new SearchNode(score[neighborAddress], neighborAddress);
                    openedNode.Add(neighborAddress, neighborNode);
                }
            }
        }

        return(new List <int>());
    }