Java – Sudoku solving method
There is something wrong with my Sudoku solving method The plan works as follows; When the circuit board starts, it is empty. The user adds several numbers to the circuit board, and then the program tries to solve it by clicking the solve button If I put the same number on the same line, everything is normal Therefore, if the user adds 1,1,0... 0 In the puzzle, it cannot solve it because its two 1s are adjacent to each other and will continue to try to find a dull, even if it is an unsolvable problem But if they are all 0 (empty), it will solve it immediately, just as ID puts 1 and 2 in the upper left corner If I just put some random numbers in it, I will detect that it cannot be solved (or if it is a valid puzzle, I will solve it)
I'm thinking about saying that when thenumber = = (row, Col) is equal to thenumber = = (line 1, Col), it should return false because it's a duplicate number
This is the code I tried to add to the solve method, which obviously failed
if ((puzzle.getNum(row,col) == a) == (puzzle.getNum(row + 1,col) == a)) { return false; }
Thank you very much for your help
Solution
Verify the puzzle like this:
>Create a Boolean array of 9 elements. > Traverse each row, each column, and 9 × 9 box
>If reading numbers, set the corresponding value in the array to true. > If it has really thrown an error (impossible puzzle). > Read row, column, or 9 × Reset Boolean array after 9 box
>Then, if the verification is successful, the solution method is called
Editing: 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 is not much time to test, but it may work The row / column variable naming may not be correct because I don't have time to find it in your code, but it doesn't matter whether it works or not