12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using System;
- using System.Collections.Generic;
- using uqac_ia_sudoku_csp.Interfaces;
- using uqac_ia_sudoku_csp.Solver.Constraints;
-
- namespace uqac_ia_sudoku_csp.Solver
- {
- public class BacktrackSearch : ISolver
- {
- private readonly INextCellChooser _nextCellChooser;
- private readonly INextNumberChooser _nextNumberChooser;
- protected IList<IConstraint> Constraints;
-
- public BacktrackSearch(INextCellChooser nextCellChooser, INextNumberChooser nextNumberChooser)
- {
- _nextCellChooser = nextCellChooser;
- _nextNumberChooser = nextNumberChooser;
- Constraints = new List<IConstraint>
- {
- new LineContraint(),
- new ColumnConstraint(),
- new BlockConstraint()
- };
- }
-
- public SolverResult Resolve(Board board)
- {
- var result = new SolverResult();
- var start = DateTime.Now;
- result.Success = RecursiveResolve(board, result);
- var end = DateTime.Now;
- result.Elapsed = end - start;
- return result;
- }
-
- protected bool RecursiveResolve(Board board, SolverResult result)
- {
- if (board.IsComplete())
- {
- return true;
- }
- int x, y;
- _nextCellChooser.SelectVariable(board, out x, out y, Constraints);
- if (x != -1 && y != -1)
- {
- foreach (var value in _nextNumberChooser.ChooseNext(Constraints, board, x, y))
- {
- ++result.TryCount;
- board.SetNumber(x, y, value);
- if (board.IsConsistent(x, y, Constraints))
- {
- ++result.ConsistentTryCount;
- if (RecursiveResolve(board, result))
- {
- return true;
- }
- }
- }
- board.ClearNumber(x, y);
- }
- return false;
- }
- }
- }
|