package 国龙算法;
public class 九宫格 {
public static void main(String[] args) {
// TODO 自动生成的方法存根
int[][] b = {
{0, 6, 1, 0, 3, 0, 0, 2, 0},
{0, 5, 0, 0, 0, 8, 1, 0, 7},
{0, 0, 0, 0, 0, 7, 0, 3, 4},
{0, 0, 9, 0, 0, 6, 0, 7, 8},
{0, 0, 3, 2, 0, 9, 5, 0, 0},
{5, 7, 0, 3, 0, 0, 9, 0, 0},
{1, 9, 0, 7, 0, 0, 0, 0, 0},
{8, 0, 2, 4, 0, 0, 0, 6, 0},
{0, 4, 0, 0, 1, 0, 2, 5, 0}};
shudu(b,0,0);
}
private static void shudu(int[][] b, int i, int j) {
// 打印数独答案
if(i==8&&j==9){
for (int i1 = 0; i1 < 9; i1++) {
for (int j1 = 0; j1 < 9; j1++) {
System.out.print(b[i1][j1] + ” “);
}
System.out.println();
}
System.out.println();
}
if(j==9){j=0;i++;}
//进行检查空元素,然后赋值
if (b[i][j] == 0) {
for (int k = 1; k <= 9; k++) {
//判断给i行j列放1-9中的任意一个数是否能满足规则
if (check(b,i, j, k)) {
//将该值赋给该空格,然后进入下一个空格
b[i][j] = k;
shudu(b,i, j + 1);
//初始化该空格
b[i][j] = 0; //还原
}
}
} else {
//如果该位置已经有值了,就进入下一个空格进行计算
shudu(b,i, j + 1);
}
}
//控制条件,进行剪枝叶
private static boolean check(int[][] b, int row, int line, int number) {
// TODO 自动生成的方法存根
for (int i1 = 0; i1 < 9; i1++) {
if (b[row][i1] == number || b[i1][line] == number) { //行和列不能有相同元素
return false;
}
}
int tempRow = row / 3; //在自己的九格内,是否有相同元素
int tempLine = line / 3;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (b[tempRow * 3 + i][tempLine * 3 + j] == number) {
return false;
}
}
}
return true;
}
}