Sudoku solve method

I have a problem with my sudoku solution method. The program works as follows; the board is empty at startup, users will add a couple of numbers to the board, and then by clicking the Solve button, the program tries to solve it. Everything works fine if I put the same number on the same line. Therefore, if the user adds 1,1,0,0 ... 0. In the puzzle he cannot solve it, because his two 1 are next to each other and will continue to aggressively try to find the sulothion, although its an insoluble puzzle. However, if they were all 0 (empty), this would immediately solve it, as if Id put 1 and 2 in the upper left corner. If I just put some random numbers in it, he would detect it as unsolvable (or solve it if it's a valid puzzle)

I ponder the lines, saying that theNumber == (row, col) equals thenNumber == (row+1, col) , it should return false because it is a duplicate number.

This is the code I tried to add to the solution method, obviously without success.

 if ((puzzle.getNum(row, col) == a) == (puzzle.getNum(row + 1, col) == a)) { return false; } 

Help with thanks

+7
source share
1 answer

Confirm the puzzle as follows:

  • Create a Boolean array of 9 elements.
  • Scroll through each row, column and field 9x9.
    • If you read the number, set the corresponding value in the array to true.
    • If this is already true, print an error (impossible riddle).
    • After reading a row, column or field 9x9 reset the boolean array.
  • Then, if the test was successful, call the solution method.

EDIT: Source Code

 public boolean checkPuzzle() { boolean[] nums = new boolean[9]; for (int row = 0; row < panel.puzzleSize; row++) { for (int cell = 0; cell < panel.puzzleSize; cell++) { if (nums[puzzle[row][cell]]) return false; nums[puzzle[row][cell]] = true; } nums = new boolean[9]; } for (int col = 0; col < panel.puzzleSize; col++) { for (int cell = 0; cell < panel.puzzleSize; cell++) { if (nums[puzzle[cell][col]]) return false; nums[puzzle[cell][col]] = true; } nums = new boolean[9]; } for (int square = 0; square < panel.puzzleSize; square++) { int squareCol = panel.squareSize * (square % panel.squareSize); int squareRow = panel.squareSize * Math.floor(square / panel.squareSize); for (int cell = 0; cell < panel.puzzleSize; cell++) { int col = cell % panel.squareSize; int row = Math.floor(cell / panel.squareSize); if (nums[puzzle[squareCol + col][squareRow + row]]) return false; nums[puzzle[squareCol + col][squareRow + row]] = true; } nums = new boolean[9]; } return true; } 

There was not too much time for testing, but this might work (?). The column / column variable names may be incorrect because I did not have time to find this in your code, but it should not make any sense to work or not.

+4
source

All Articles