I am coding this Sudoku Solver with the following algorithm:
Given a grid which is assumed to be a valid sudoku puzzle and exists at least 1 solution, it’ll find the first solution and return it.
The puzzle is stored in a 2D array representing 9×9 slots.
If a solution does not exist, it returns a puzzle where puzzle[0][0] = 0, else all slots in the puzzle is supposedly filled up with values (1-9).
The algorithm is a bruteforce recursive method:
- It searches the puzzle row by row for a single slot.
- The method
possibleValuesInGrid()returns the possible values that can fit into the slot based on the current puzzle and its existing values. - If there are no possible values to be placed in the slot, it returns a False (puzzle[0][0] = 0)
- ELSE, it pops one of the values from the
LinkedListof possible values and insert into the slot, and recursively call the same method again till all the slots are filled up.
The code is being hosted at pastebin so I don’t flood this page. I suspect there might be a logic error somewhere although its a bruteforce method, or even a bug that I can’t seem to figure.
I have hardcoded some system printlines to read through to figure for logic error, however I couldn’t figure out where.
Also, how it stopped at [8][4] is also curious.
- utils/PuzzleSolverBruteForce.java
- utils/PuzzleGenerator.java (not completed, but the dependency part for BruteForce class is done in here, and completed)
- runtime printlines for logic debugging.
Your code fails because you are using clone on a multi-dimensional array (line 44). A clone only give you a shallow copy and in the case of a 2-dimensional array, that’s not good enough. You need System.arraycopy(), but on each row, so call something like
You can see the symptom of your failed clone on your log on line 49, where the code suddenly sees a puzzle with an empty slot at 0:0.