private static int SolveBoard(List <string> board) { var boardsToExplore = new Queue <BoardWithLevel>(); var startingBoard = new BoardWithLevel(board, FindEmptySquare(board)); boardsToExplore.Enqueue(startingBoard); var seenBoards = new Dictionary <string, bool>(); while (boardsToExplore.Count > 0) { var currentBoard = boardsToExplore.Dequeue(); if (BoardIsComplete(currentBoard)) { return(currentBoard.Level); } var currentBoardKey = string.Join("", currentBoard); if (seenBoards.ContainsKey(currentBoardKey)) { continue; } seenBoards.Add(currentBoardKey, true); var numberOfMisplacedPieces = NumberOfMisplacedPieces(currentBoard); var minimumTotalMoves = (numberOfMisplacedPieces - 1) + currentBoard.Level; if (currentBoard.Level < 10 && minimumTotalMoves < 11) { var emptySquare = currentBoard.EmptySquarePosition; var possibleMoves = GetAllPossibleMoves(emptySquare); foreach (var move in possibleMoves) { var newBoard = CreateUpdatedBoard(currentBoard, emptySquare, move); var newBoardKey = string.Join("", newBoard); if (!seenBoards.ContainsKey(newBoardKey)) { boardsToExplore.Enqueue(new BoardWithLevel(newBoard.ToList(), move, currentBoard.Level + 1)); } } } } return(11); }
private static string[] CreateUpdatedBoard(BoardWithLevel currentBoard, Position emptySquare, Position move) { var newBoard = new string[5]; currentBoard.CopyTo(newBoard); var theRow = newBoard[emptySquare.Row].ToCharArray(); theRow[emptySquare.Column] = newBoard[move.Row][move.Column]; newBoard[emptySquare.Row] = new string(theRow); theRow = newBoard[move.Row].ToCharArray(); theRow[move.Column] = ' '; newBoard[move.Row] = new string(theRow); return(newBoard); }