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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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 bool Resolve(Board board)
  21. {
  22. return RecursiveResolve(board);
  23. }
  24. protected bool RecursiveResolve(Board board)
  25. {
  26. if (board.IsComplete())
  27. {
  28. return true;
  29. }
  30. int x, y;
  31. SelectVariable(board, out x, out y);
  32. foreach (var value in GetDomainValues(board))
  33. {
  34. board.SetNumber(x, y, value);
  35. if (IsConsistent(board, x, y))
  36. {
  37. if (RecursiveResolve(board))
  38. {
  39. return true;
  40. }
  41. }
  42. }
  43. board.ClearNumber(x, y);
  44. return false;
  45. }
  46. protected void SelectVariable(Board board, out int x, out int y)
  47. {
  48. for (var xx = 0; xx < board.Size; ++xx)
  49. {
  50. for (var yy = 0; yy < board.Size; ++yy)
  51. {
  52. if (board.GetNumber(xx, yy) == null)
  53. {
  54. x = xx;
  55. y = yy;
  56. return;
  57. }
  58. }
  59. }
  60. x = -1;
  61. y = -1;
  62. }
  63. protected IEnumerable<int> GetDomainValues(Board board)
  64. {
  65. return Enumerable.Range(0, board.Size);
  66. }
  67. protected bool IsConsistent(Board board, int x, int y)
  68. {
  69. return Constraints.All(constraint => constraint.Check(board, x, y));
  70. }
  71. }
  72. }