コード例 #1
0
ファイル: SudokuGrid.cs プロジェクト: Chris1712/SudokoSolver
        public static SudokuGrid RecursiveSolve(SudokuGrid gridToSolve)
        {
            if (!gridToSolve.IsValid)
            {
                return null;
            }
            if (gridToSolve.IsComplete)
            {
                return gridToSolve;
            }

            // So we have a grid that's incomplete and might have solutions, so:
            var nextPosTuple = gridToSolve.NextPositionToPopulate();

            foreach (var possibleEntry in nextPosTuple.Item3)
            {
                var sudokuGridToAmend = new char[9, 9];
                Array.Copy(gridToSolve.sudokuArray, sudokuGridToAmend, 81);

                sudokuGridToAmend[nextPosTuple.Item1, nextPosTuple.Item2] = possibleEntry;

                // Recursion is magic!
                var newGridToSolve = new SudokuGrid(sudokuGridToAmend);
                var solvedGrid = RecursiveSolve(newGridToSolve);

                if (solvedGrid != null)
                {
                    return solvedGrid;
                }
            }

            // Otherwise the grid we've been given has no solutions, so
            return null;
        }