コード例 #1
0
        public static void PrintFullPath(Dictionary <Day11Board, Day11Board> cameFrom, Day11Board currentBoard)
        {
            Day11Board board = currentBoard;

            Console.WriteLine(board.ToString());
            int cnt = 0;

            while (cameFrom.ContainsKey(board))
            {
                board = cameFrom[board];
                Console.WriteLine(board.ToString());
                cnt++;
            }
            Console.WriteLine($"Solution found in {cnt} moves");
        }
コード例 #2
0
        public static void Day11()
        {
            Day11Board currentBoard = new Day11Board();

            currentBoard.fScore = currentBoard.distance;
            currentBoard.gScore = 0;

            Dictionary <Day11Board, Day11Board> cameFrom = new Dictionary <Day11Board, Day11Board>();
            List <Day11Board> openSet = new List <Day11Board>()
            {
                currentBoard
            };
            List <Day11Board> closedSet = new List <Day11Board>();

            bool success = false;
            int  nodeNum = 0;

            while (openSet.Count > 0)
            {
                openSet.Sort();
                currentBoard = openSet[0];
                Console.WriteLine(currentBoard);
                if (currentBoard.Success)
                {
                    Console.WriteLine($"Success! fScore: {currentBoard.fScore} gScore: {currentBoard.gScore}");
                    success = true;
                    break;
                }

                openSet.Remove(currentBoard);
                closedSet.Add(currentBoard);
                foreach (Day11Board childBoard in currentBoard.GetAllBoards())
                {
                    int nextGScore = currentBoard.gScore + 1;

                    Day11Board existingBoard = openSet.FirstOrDefault(b => b.Equals(childBoard));
                    if (existingBoard != null && nextGScore < existingBoard.gScore)
                    {
                        openSet.Remove(existingBoard);
                    }

                    existingBoard = closedSet.FirstOrDefault(b => b.Equals(childBoard));
                    if (existingBoard != null && nextGScore < existingBoard.gScore)
                    {
                        closedSet.Remove(existingBoard);
                    }

                    if (!openSet.Contains(childBoard) && !closedSet.Contains(childBoard))
                    {
                        childBoard.gScore = nextGScore;
                        childBoard.fScore = childBoard.gScore + childBoard.distance;
                        openSet.Add(childBoard);
                        cameFrom[childBoard] = currentBoard;
                    }
                }

                nodeNum++;
            }

            PrintFullPath(cameFrom, currentBoard);
            if (!success)
            {
                Console.WriteLine("Could not find a solution");
            }
        }