The Tricks of Sudoku Solver Algorithm Java

By now just about everyone has seen the Java sudoku solver algorithm that’s made the rounds across the Internet. Plenty of people have already seen the source code, but they might be curious as to how it works. The majority of the methods seen require input to the solution from the command line. Perhaps the most innovative way of doing this was to input each individual row of the problem as a string, and show the whole sudoku board as an array.

Solving a Sudoku Puzzle

sudoku solver algorithm javaThose who are working on writing Java sudoku solver might want to have a look at an eight queens puzzle or some other similar one. All of these backtracking puzzles use some form of the same source code, which helps when it comes time to solving the problem.

Even those without experience should be able to understand the way the Java source code parses input though:

public static void main(String[] args) {

int[][] array = parseProblem(args);

writeMatrix(array);

if (solve(0,0,array))

writeMatrix(array);

Here the Java sudoku solver algorithm takes what the user writes on the command line and places it into arrays for use later. The actual solving work places the data taken from arrays and sending it through a series of loops that ensure that each row, not box, includes every number from 1-9 only once. This is sort of the trick considering that the program looks at a sudoku problem a little differently from most human solvers.

Each loop would then print the numbers across in rows as follows:

static boolean solve(int i, int j, int[][] boxes) {

if (i == 9) {

i = 0;

if (++j == 9)

return true;

}

if (boxes[i][j] != 0)

return solve(i+1,j,boxes);

Sudoku Source Code

sudoku solver java source codeNote that the actual Java source code checks to make sure that each box is unfilled, and skips filling it in. By the time all these loops run everything has been filled. These are the sorts of quick little programming tricks professionals can add to make an applet work right the first time.

Still not getting the sudoku solver algorithm java thing? Ask out team for some help!