Ejemplo n.º 1
0
        public SudokuSolver(SudokuPuzzle puzzle)
        {
            if (puzzle == null)
            {
                throw new ArgumentNullException("puzzle");
            }

            this.Puzzle = puzzle.Clone() as SudokuPuzzle;
        }
Ejemplo n.º 2
0
        public void SudokuPuzzle_CanCloneItself()
        {
            var puzzle = new SudokuPuzzle();
            puzzle.SetValue(1, 4, SudokuValue.NINE);
            puzzle.SetValue(2, 3, SudokuValue.FIVE);

            var clone = puzzle.Clone() as SudokuPuzzle;
            puzzle.ClearBoard();

            Assert.AreEqual(SudokuValue.NINE, clone.GetValue(1, 4));
            Assert.AreEqual(SudokuValue.FIVE, clone.GetValue(2, 3));
        }
Ejemplo n.º 3
0
        private static SudokuPuzzle Backtracking(SudokuPuzzle puzzle)
        {
            if (puzzle.IsComplete)
            {
                return(puzzle);
            }

            if (_stopwatch.Elapsed.Minutes >= 5)
            {
                return(null);
            }

            var cell = puzzle.NextCell();

            // Keep track of first three steps
            if (Steps.Count < 3)
            {
                Steps.Add(new SudokuPuzzleStepModel
                {
                    Degree      = puzzle.GetDegree(cell),
                    DomainSize  = cell.Domain.Count,
                    SelectedCol = cell.Col,
                    SelectedRow = cell.Row
                });
            }

            foreach (var value in cell.Domain)
            {
                // Generate next node
                var clone = puzzle.Clone();
                clone.SetCellValue(cell.Row, cell.Col, value);

                // If there exists a cell with an empty domain after forward checking, backtrack
                if (clone.MinRemainingValue()?.Domain.Count == 0)
                {
                    continue;
                }

                var result = Backtracking(clone);
                if (result != null)
                {
                    return(result);
                }
            }
            return(null);
        }