Guest User

Untitled

a guest
Aug 17th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. package sudoku;
  2. import static sudoku.Board.EMPTY_CELL;
  3. import static sudoku.Board.GRID_SIZE;
  4.  
  5. /**
  6. * This class implements the solving algorithm, It is separated from
  7. * the board logic
  8. *
  9. * The visibility of this class is package, as it is not the external API
  10. * @author vincent
  11. *
  12. */
  13. class Solver {
  14.  
  15. private final Board board;
  16.  
  17. /**
  18. * Constructor
  19. * @param input a 9x9 array representing a sudoku, empty cells are 0
  20. */
  21. Solver(int[][] input) {
  22. this.board = new Board(input);
  23. }
  24. /**
  25. * Method to solve the sudoku "in-place" (without creating/copying with a new array)
  26. * @return true if the sudoku is successfully solved
  27. */
  28. boolean solve() {
  29. return solve(0,0);
  30. }
  31.  
  32. /**
  33. * Returns the board object, useful for pretty-printing of the sudoku
  34. */
  35. Board getBoard() {
  36. return board;
  37. }
  38.  
  39. /**
  40. * Backtracking recursive algorithm to solve sudoku
  41. */
  42. private boolean solve(int row, int col) {
  43. if (row == GRID_SIZE) {
  44. row = 0;
  45. if (++col == GRID_SIZE) {
  46. return true;
  47. }
  48. }
  49. if (board.getCell(row, col) != EMPTY_CELL) {
  50. return solve(row+1,col);
  51. }
  52. // For all possible values
  53. for(int val = 1; val <= GRID_SIZE; val++) {
  54. if (isMoveOK(row, col, val)) {
  55. board.setCell(row, col, val);
  56. if (solve(row+1, col)) {
  57. return true;
  58. }
  59. }
  60. }
  61. // Reset the cell to EMPTY to do recursive backtrack and try again
  62. board.setCell(row, col, EMPTY_CELL);
  63. return false;
  64. }
  65.  
  66.  
  67. private boolean isMoveOK(int row, int col, int val) {
  68. return ! ( arrayContains(board.getRow(row), val)
  69. || arrayContains(board.getColumn(col), val)
  70. || arrayContains(board.getRegion(row, col), val));
  71. }
  72.  
  73. private boolean arrayContains(int[] array, int val) {
  74. for (int arrayVal : array) {
  75. if (arrayVal == val) {
  76. // return true and stop the iteration
  77. return true;
  78. }
  79. }
  80. return false;
  81. }
  82. }
Add Comment
Please, Sign In to add comment