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 2.0KB

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