12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- 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 INextValueChooser _nextValueChooser;
- protected IList<IConstraint> Constraints;
-
- public BacktrackSearch(INextValueChooser nextValueChooser)
- {
- _nextValueChooser = nextValueChooser;
- Constraints = new List<IConstraint>
- {
- new LineContraint(),
- new ColumnConstraint(),
- new BlockConstraint()
- };
- }
-
- public SolverResult Resolve(Board board)
- {
- var domain = Enumerable.Range(0, board.Size).ToList();
- var result = new SolverResult();
- var start = DateTime.Now;
- result.Success = RecursiveResolve(board, result, domain);
- var end = DateTime.Now;
- result.Elapsed = end - start;
- return result;
- }
-
- protected bool RecursiveResolve(Board board, SolverResult result, IList<int> domain)
- {
- if (board.IsComplete())
- {
- return true;
- }
- int x, y;
- _nextValueChooser.SelectVariable(board, out x, out y, Constraints);
- if (x != -1 && y != -1)
- {
- foreach (var value in domain)
- {
- ++result.TryCount;
- board.SetNumber(x, y, value);
- if (board.IsConsistent(x, y, Constraints))
- {
- ++result.ConsistentTryCount;
- if (RecursiveResolve(board, result, domain))
- {
- return true;
- }
- }
- }
- board.ClearNumber(x, y);
- }
- return false;
- }
- }
- }
|