Sudoku solve method
I've a problem with my sudoku solving method. The program works like this; the board is empty when started, the users adds a couple of numbers to the board and then by hitting a Solve-button the program tries to solve it. Everything works fine besides if I put the same number in the same row. So if the user adds 1,1,0,0 ... 0. In the puzzle it can't solve it because its two 1's next to each other and will just go on forever trying to find a sulotion even though its an unsolvable puzzle. However if they were all 0's(empty) it would solve it right away, same as if Id put 1 and 2 in the top left corner. If I'd just put some random numbers in it will detect it as unsolvable (or will solve it if it's a valid puzzle)
I'm thinking around the lines of saying, when theNumber == (row, col) equals thenNumber == (row+1, col)
, it should return false
because it's a duplicated number.
This is the code I tried to add in the solve method, obviously without success.
if ((puzzle.getNum(row, col) == a) == (puzzle.getNum(row + 1, col) == a)) {
return false;
}
Help is greatly appreciated
Validate the puzzle like this:
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;
}
Didn't have too much time to test out, but it might work (?). The row/col variable namings might be incorrect, because I didn't have time to find that in your code, but it shouldn't matter for it to work or not.
链接地址: http://www.djcxy.com/p/70184.html下一篇: 数独解决方法