Esempio n. 1
0
        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;
        }