コード例 #1
0
ファイル: Solver.cs プロジェクト: JStalnac/Sudoku-Game
        /// <summary>
        /// Creates solved state to the game board and returns whether the puzzle solved.
        /// </summary>
        /// <param name="UseRandomGenerator">Set it to true to see a different result for each solution.</param>
        /// <returns>Returns whether the board solved.</returns>
        public bool SolveThePuzzle(bool UseRandomGenerator = true)
        {
            // Return false if the current state is board is not valid.
            if (!CheckTableStateIsValid())
            {
                return(false);
            }

            // Init protected index list to protect the current state of the board while backtracking.
            InitIndexListOfTheAlreadyFilledCells();

            // Clear the blacklist
            ClearBlackList();

            int currentCellIndex = 0;

            // Iterate all the cells of the board.
            while (currentCellIndex < SudokuBoard.TOTAL_CELLS)
            {
                // If the current cell index is protected(which means it was inner the current state of the board), pass it.
                if (TheIndexesOfFilledCells.Contains(currentCellIndex))
                {
                    ++currentCellIndex;
                    continue;
                }

                // Clear blacklists of the indexes after the current index.
                ClearBlackList(startCleaningFromThisIndex: currentCellIndex + 1);

                Cell currentCell = SudokuBoard.GetCell(cellIndex: currentCellIndex);

                int theFoundValidNumber = GetValidNumberForTheCell(currentCellIndex, UseRandomGenerator);

                // No valid number found for the cell. Let's backtrack.
                if (theFoundValidNumber == 0)
                {
                    // Let's backtrack
                    currentCellIndex = BacktrackTo(currentCellIndex);
                }
                else
                {
                    // Set found valid value to current cell.
                    SudokuBoard.SetCellValue(theFoundValidNumber, currentCell.Index);
                    ++currentCellIndex;
                }
            }

            return(true);
        }