Java program to solve Sudoko problem

Hi All,
  we know Sudoku is a famous game or brain twister to time pass or improve your logical skills.
So thing is that what if some one ask to solve Sudoku in seconds ? or if you are a programmer
what if some one ask you to write Sudoku program ?

Here is the solution for that.
For Quick inputing purpose am just initializing matrix on program(hard coding) instead of taking inputs from standard io or command line.


public class Sudoku {
public static void main(String[] args) {
int[][] matrix = {{0, 4, 3, 7, 0, 0, 9, 0, 8},
{0, 0, 5, 0, 3, 0, 0, 0, 0}, {0, 1, 0, 0, 0, 0, 3, 0, 0},
{6, 0, 0, 0, 2, 7, 0, 0, 0}, {4, 0, 7, 0, 0, 0, 1, 0, 3},
{0, 0, 0, 5, 4, 0, 0, 0, 9}, {0, 0, 2, 0, 0, 0, 0, 3, 0},
{0, 0, 0, 0, 5, 0, 4, 0, 0}, {5, 0, 4, 0, 0, 1, 2, 6, 0}};
myWriteMat(matrix);
solve(0, 0, matrix);
myWriteMat(matrix);
}

static void myWriteMat(int matrix[][]) {
int n = (matrix.length * 3) - 2;
for (int i = 0; i < matrix.length; i++) {
if (i % 3 == 0) {
drawHorizontal(n);
}
// System.out.print("| ");
for (int j = 0; j < matrix.length; j++) {
if (j % 3 == 0) {
System.out.print("| ");
}
System.out.print(matrix[i][j] + " ");
}
System.out.println("|");
}
drawHorizontal(n);
}
static void drawHorizontal(int n) {
for (int j = 0; j < n; j++) {
if (j == 0 || j == n - 1) {
System.out.print(" ");
} else {
System.out.print("-");
}
}
System.out.println();
}

static boolean solve(int i, int j, int[][] cells) {
if (i == 9) {
i = 0;
if (++j == 9)
return true;
}
if (cells[i][j] != 0) // skip filled cells
return solve(i + 1, j, cells);

for (int val = 1; val <= 9; ++val) {
if (legal(i, j, val, cells)) {
cells[i][j] = val;
if (solve(i + 1, j, cells))
return true;
}
}
cells[i][j] = 0; // reset on backtrack
return false;
}

static boolean legal(int i, int j, int val, int[][] cells) {
for (int k = 0; k < 9; ++k) // row
if (val == cells[k][j])
return false;

for (int k = 0; k < 9; ++k) // col
if (val == cells[i][k])
return false;

int boxRowOffset = (i / 3) * 3;
int boxColOffset = (j / 3) * 3;
for (int k = 0; k < 3; ++k) // box
for (int m = 0; m < 3; ++m)
if (val == cells[boxRowOffset + k][boxColOffset + m])
return false;

return true; // no violations, so it's legal
}

}

Credits for this program:
Bob carpenter
you can find the original program click here

Comments

Popular posts from this blog

Small virus code to hang your friend's system

How to use Remote Desktop