예제 #1
0
        public SudokuBrett Solve(SudokuBrett sudokuBrett)
        {
            PossibleValues[,] set = sudokuBrett.InitPossibleValues();
            IterativeSolveCells(sudokuBrett, set);

            if (sudokuBrett.GetUnsolved() == 0) //success, solution found
            {
                return(sudokuBrett);
            }


            //if not solved, try..
            if (sudokuBrett.GetUnsolved() > 0)
            {
                //find first posssible valueset..
                var firstWithoutValue = set.FirstWithoutValue();

                var orginal = new SudokuBrett(sudokuBrett);
                foreach (var posssible in firstWithoutValue.value)
                {
                    try
                    {
                        sudokuBrett.GuessSet(firstWithoutValue.r, firstWithoutValue.c, posssible);
                        sudokuBrett = Solve(sudokuBrett);

                        if (sudokuBrett.GetUnsolved() == 0) //success, solution found
                        {
                            return(sudokuBrett);
                        }
                        else
                        {
                            //didnt succesfully solved with this guessed number, try next...
                            sudokuBrett = orginal;
                        }
                    }
                    catch (Exception)
                    {
                        sudokuBrett = orginal;
                    }
                }
            }

            //no solution found
            return(sudokuBrett);
        }
예제 #2
0
        private void IterativeSolveCells(SudokuBrett sudokuBrett, PossibleValues[,] set)
        {
            int updated = 1;

            while (updated > 0)
            {
                sudokuBrett.RemoveUsedFromPossibleValues(set);
                set.ReducePossibleValues();

                if (!sudokuBrett.IsLegal(set))
                {
                    throw new Exception($"Illegal settings ");
                }

                updated = sudokuBrett.UpdateNextPossibleValues(set);
            }

            return;
        }