Reputation: 17314
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 9x9 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:
possibleValuesInGrid()
returns the possible values that can fit into the slot based on the current puzzle and its existing values.LinkedList
of 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.
Upvotes: 0
Views: 208
Reputation: 2042
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
public void 2dArrayCopy(int[][] source,int[][] target) {
for (int a=0; a<source.length; a++) {
System.arraycopy(source[a],0,target[a],0,source[a].length);
}
}
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.
Upvotes: 5