深度搜索(递归)
采用Java解数独还是第一次。由于Java的运算较Python快很多,在算法上就没有那么多讲究了。验证了几个高难度数独,都是秒解。解题的思路采用深度搜索递归方式进行。
package good;
public class SDK {
static int[][] arr1={{8, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 3, 6, 0, 0, 0, 0, 0},
{0, 7, 0, 0, 9, 0, 2, 0, 0},
{0, 5, 0, 0, 0, 7, 0, 0, 0},
{0, 0, 0, 0, 4, 5, 7, 0, 0},
{0, 0, 0, 1, 0, 0, 0, 3, 0},
{0, 0, 1, 0, 0, 0, 0, 6, 8},
{0, 0, 8, 5, 0, 0, 0, 1, 0},
{0, 9, 0, 0, 0, 0, 4, 0, 2}};
static int[][] arr2={{0, 0, 0, 0, 0, 2, 0, 5, 0},
{0, 7, 8, 0, 0, 0, 3, 0, 0},
{0, 0, 0, 0, 0, 4, 0, 0, 0},
{5, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 0, 0, 0, 1, 0, 0},
{0, 0, 0, 0, 3, 0, 7, 0, 8},
{2, 0, 0, 0, 0, 0, 0, 4, 0},
{0, 0, 0, 0, 0, 5, 0, 9, 0},
{0, 1, 0, 0, 7, 0, 0, 0, 0}};
static int[][] arr3={{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 6, 0, 3, 0, 4, 0, 2, 0},
{0, 0, 0, 0, 0, 0, 0, 7, 5},
{0, 0, 0, 0, 0, 0, 0, 0, 0},
{0, 0, 0, 6, 8, 0, 3, 0, 0},
{1, 0, 5, 0, 7, 0, 0, 0, 0},
{0, 0, 0, 0, 5, 0, 0, 0, 0},
{0, 3, 0, 0, 0, 0, 4, 0, 0},
{8, 0, 0, 9, 0, 0, 0, 0, 0}};
static int[][] arr4={{0, 0, 5, 3, 0, 0, 0, 0, 0},
{8, 0, 0, 0, 0, 0, 0, 2, 0},
{0, 7, 0, 0, 1, 0, 5, 0, 0},
{4, 0, 0, 0, 0, 5, 3, 0, 0},
{0, 1, 0, 0, 7, 0, 0, 0, 6},
{0, 0, 3, 2, 0, 0, 0, 8, 0},
{0, 6, 0, 5, 0, 0, 0, 0, 9},
{0, 0, 4, 0, 0, 0, 0, 3, 0},
{0, 0, 0, 0, 0, 9, 7, 0, 0}};
static int[][] arr5={{0, 8, 0, 0, 0, 0, 0, 0, 0},
{9, 0, 0, 5, 0, 0, 7, 0, 0},
{0, 0, 1, 0, 0, 4, 0, 0, 2},
{8, 0, 0, 0, 0, 1, 2, 0, 4},
{0, 0, 0, 0, 9, 0, 0, 0, 0},
{0, 5, 3, 7, 0, 0, 0, 9, 0},
{0, 6, 0, 0, 0, 2, 0, 8, 0},
{0, 0, 2, 1, 0, 0, 0, 0, 7},
{0, 0, 0, 0, 0, 0, 6, 0, 0}};
static int[][] arr= arr1;
static long startTime = System.currentTimeMillis();
public static void main(String[] args) {
// TODO Auto-generated method stub
dfs(0);
System.out.println("无解!");
}
public static boolean logic(int y, int x, int k) {
for(int i=0;i<9;i+=1) {
if(k==arr[y][i]) {
return false;
}
}
for(int j=0;j<9;j+=1) {
if(k==arr[j][x]) {
return false;
}
}
int h=(y / 3) * 3 * 9 + (x / 3) * 3;
for(int head=h;head<=h+18;head+=9) {
for(int j=head;j<head+3;j+=1) {
if(k==arr[j/9][j%9]){
return false;
}
}
}
return true;
}
public static void show() {
for(int i=0;i<9;i+=1) {
for(int j=0;j<9;j+=1) {
System.out.print(arr[i][j]+" ");
}
System.out.println("");
}
System.out.println("");
long endTime = System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间:" + (endTime - startTime)*0.001 + "s");
System.exit(0);
}
public static void dfs(int m) {
if(arr[m/9][m%9]!=0) {
if(m!=80) {
dfs(m+1);}
else{
show();
}
}
for(int avail=1;avail<=9;avail+=1) {
if(arr[m/9][m%9]==0 && logic(m/9,m%9,avail)) {
arr[m/9][m%9]=avail;
if(m==80) {
show();
}
dfs(m + 1);
arr[m/9][m%9]=0;
}
}
}
}
8 1 2 7 5 3 6 4 9
9 4 3 6 8 2 1 7 5
6 7 5 4 9 1 2 8 3
1 5 4 2 3 7 8 9 6
3 6 9 8 4 5 7 2 1
2 8 7 1 6 9 5 3 4
5 2 1 9 7 4 3 6 8
4 3 8 5 2 6 9 1 7
7 9 6 3 1 8 4 5 2
程序运行时间:0.021s