12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- 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
- {
- protected IList<IConstraint> Constraints;
-
- public BacktrackSearch()
- {
- Constraints = new List<IConstraint>
- {
- new LineContraint(),
- new ColumnConstraint(),
- new BlockConstraint()
- };
- }
-
- public SolverResult Resolve(Board board)
- {
- var result = new SolverResult();
- result.Success = RecursiveResolve(board, result);
- return result;
- }
-
- protected bool RecursiveResolve(Board board, SolverResult result)
- {
- if (board.IsComplete())
- {
- return true;
- }
- int x, y;
- SelectVariable(board, out x, out y);
- foreach (var value in GetDomainValues(board))
- {
- ++result.TryCount;
- board.SetNumber(x, y, value);
- if (IsConsistent(board, x, y))
- {
- if (RecursiveResolve(board, result))
- {
- return true;
- }
- }
- }
- board.ClearNumber(x, y);
- return false;
- }
-
- protected void SelectVariable(Board board, out int x, out int y)
- {
- for (var xx = 0; xx < board.Size; ++xx)
- {
- for (var yy = 0; yy < board.Size; ++yy)
- {
- if (board.GetNumber(xx, yy) == null)
- {
- x = xx;
- y = yy;
- return;
- }
- }
- }
- x = -1;
- y = -1;
- }
-
- protected IEnumerable<int> GetDomainValues(Board board)
- {
- return Enumerable.Range(0, board.Size);
- }
-
- protected bool IsConsistent(Board board, int x, int y)
- {
- return Constraints.All(constraint => constraint.Check(board, x, y));
- }
- }
- }
|