class sudokumatrix {
private int[][] matrix = new int[][] {
{0, 5, 0, 6, 0, 1, 0, 0, 0},
{0, 0, 7, 0, 9, 0, 0, 2, 0},
{3, 0, 0, 0, 0, 4, 0, 0, 1},
{9, 0, 0, 0, 0, 0, 1, 3, 0},
{0, 0, 8, 0, 5, 0, 7, 0, 0},
{0, 2, 6, 0, 0, 0, 0, 0, 8},
{7, 0, 0, 9, 0, 0, 0, 0, 5},
{0, 9, 0, 0, 4, 0, 3, 0, 0},
{0, 0, 0, 2, 0, 8, 0, 1, 0},
};
public void run(){
calc();
}
private void calc() {
int[] coordinate = getnextdata();
int m = coordinate[0];
int n = coordinate[1];
for (int k = 1; k <= 9; k++) {
if(checknumber(m,n,k)) {
matrix[m][n] = k;
//system.out.println( m + , + n + with + k );
if ( getnextdata() == null ) {
print(matrix);
}
else {
calc();
}
}
}
matrix[m][n] = 0;
}
private int[] getnextdata(){
for (int row = 0; row < 9; row++) {
for (int col = 0; col < 9; col++) {
if (matrix[row][col] == 0) {
int[] coordinateofemptysquare = {row, col};
return coordinateofemptysquare;
}
}
}
return null;
}
private boolean checknumber(int row, int col, int n) {
for (int i = 0; i < 9; i++) {
if (matrix[row][i] == n || matrix[i][col] == n) {
return false;
}
}
int[] lefttop = {row - (row % 3), col - (col % 3)};
for (int r = lefttop[0]; r <= lefttop[0] + 2; r++) {
for (int c = lefttop[1]; c <= lefttop[1] + 2; c++) {
if (matrix[r][c] == n) {
return false;
}
}
}
return true;
}
public void print(int[][] grid) {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
system.out.print(grid[i][j] + );
}
system.out.println();
}
system.out.println();
}
}
以上就是数独小算法的实例详解的详细内容。