You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BacktrackSearch.cs 1.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. using System.Collections.Generic;
  2. using System.Linq;
  3. using uqac_ia_sudoku_csp.Interfaces;
  4. using uqac_ia_sudoku_csp.Solver.Constraints;
  5. namespace uqac_ia_sudoku_csp.Solver
  6. {
  7. public class BacktrackSearch : ISolver
  8. {
  9. private readonly INextValueChooser _nextValueChooser;
  10. protected IList<IConstraint> Constraints;
  11. public BacktrackSearch(INextValueChooser nextValueChooser)
  12. {
  13. _nextValueChooser = nextValueChooser;
  14. Constraints = new List<IConstraint>
  15. {
  16. new LineContraint(),
  17. new ColumnConstraint(),
  18. new BlockConstraint()
  19. };
  20. }
  21. public SolverResult Resolve(Board board)
  22. {
  23. var domain = Enumerable.Range(0, board.Size).ToList();
  24. var result = new SolverResult();
  25. result.Success = RecursiveResolve(board, result, domain);
  26. return result;
  27. }
  28. protected bool RecursiveResolve(Board board, SolverResult result, IList<int> domain)
  29. {
  30. if (board.IsComplete())
  31. {
  32. return true;
  33. }
  34. int x, y;
  35. _nextValueChooser.SelectVariable(board, out x, out y, Constraints);
  36. if (x != -1 && y != -1)
  37. {
  38. foreach (var value in domain)
  39. {
  40. ++result.TryCount;
  41. board.SetNumber(x, y, value);
  42. if (board.IsConsistent(x, y, Constraints))
  43. {
  44. if (RecursiveResolve(board, result, domain))
  45. {
  46. return true;
  47. }
  48. }
  49. }
  50. board.ClearNumber(x, y);
  51. }
  52. return false;
  53. }
  54. }
  55. }