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 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 INextCellChooser _nextCellChooser;
  10. private readonly INextNumberChooser _nextNumberChooser;
  11. protected IList<IConstraint> Constraints;
  12. public BacktrackSearch(INextCellChooser nextCellChooser, INextNumberChooser nextNumberChooser)
  13. {
  14. _nextCellChooser = nextCellChooser;
  15. _nextNumberChooser = nextNumberChooser;
  16. Constraints = new List<IConstraint>
  17. {
  18. new LineContraint(),
  19. new ColumnConstraint(),
  20. new BlockConstraint()
  21. };
  22. }
  23. public SolverResult Resolve(Board board)
  24. {
  25. var result = new SolverResult();
  26. var start = DateTime.Now;
  27. result.Success = RecursiveResolve(board, result);
  28. var end = DateTime.Now;
  29. result.Elapsed = end - start;
  30. return result;
  31. }
  32. protected bool RecursiveResolve(Board board, SolverResult result)
  33. {
  34. if (board.IsComplete())
  35. {
  36. return true;
  37. }
  38. int x, y;
  39. _nextCellChooser.SelectVariable(board, out x, out y, Constraints);
  40. if (x != -1 && y != -1)
  41. {
  42. foreach (var value in _nextNumberChooser.ChooseNext(Constraints, board, x, y))
  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))
  50. {
  51. return true;
  52. }
  53. }
  54. }
  55. board.ClearNumber(x, y);
  56. }
  57. return false;
  58. }
  59. }
  60. }