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.2KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. protected IList<IConstraint> Constraints;
  11. public BacktrackSearch()
  12. {
  13. Constraints = new List<IConstraint>
  14. {
  15. new LineContraint(),
  16. new ColumnConstraint(),
  17. new BlockConstraint()
  18. };
  19. }
  20. public SolverResult Resolve(Board board)
  21. {
  22. var result = new SolverResult();
  23. result.Success = RecursiveResolve(board, result);
  24. return result;
  25. }
  26. protected bool RecursiveResolve(Board board, SolverResult result)
  27. {
  28. if (board.IsComplete())
  29. {
  30. return true;
  31. }
  32. int x, y;
  33. SelectVariable(board, out x, out y);
  34. foreach (var value in GetDomainValues(board))
  35. {
  36. ++result.TryCount;
  37. board.SetNumber(x, y, value);
  38. if (IsConsistent(board, x, y))
  39. {
  40. if (RecursiveResolve(board, result))
  41. {
  42. return true;
  43. }
  44. }
  45. }
  46. board.ClearNumber(x, y);
  47. return false;
  48. }
  49. protected void SelectVariable(Board board, out int x, out int y)
  50. {
  51. for (var xx = 0; xx < board.Size; ++xx)
  52. {
  53. for (var yy = 0; yy < board.Size; ++yy)
  54. {
  55. if (board.GetNumber(xx, yy) == null)
  56. {
  57. x = xx;
  58. y = yy;
  59. return;
  60. }
  61. }
  62. }
  63. x = -1;
  64. y = -1;
  65. }
  66. protected IEnumerable<int> GetDomainValues(Board board)
  67. {
  68. return Enumerable.Range(0, board.Size);
  69. }
  70. protected bool IsConsistent(Board board, int x, int y)
  71. {
  72. return Constraints.All(constraint => constraint.Check(board, x, y));
  73. }
  74. }
  75. }