深度优先

这个家伙好懒,除了文章什么都没留下

0%

【算法】“数独”游戏-Java-dfs搜索算法

你一定听说过“数独”游戏。
如【图1.png】,玩家需要根据9×9盘面上的已知数字,推理出所有剩余空格的数字,并满足每一行、每一列、每一个同色九宫内的数字均含1-9,不重复。

数独的答案都是唯一的,所以,多个解也称为无解。

本图的数字据说是芬兰数学家花了3个月的时间设计出来的较难的题目。但对会使用计算机编程的你来说,恐怕易如反掌了。

本题的要求就是输入数独题目,程序输出数独的唯一解。我们保证所有已知数据的格式都是合法的,并且题目有唯一的解。

格式要求,输入9行,每行9个字符,0代表未知,其它数字为已知。
输出9行,每行9个数字表示数独的解。

例如:
输入(即图中题目):
005300000
800000020
070010500
400005300
010070006
003200080
060500009
004000030
000009700

程序应该输出:
145327698
839654127
672918543
496185372
218473956
753296481
367542819
984761235
521839764

再例如,输入:
800000000
003600000
070090200
050007000
000045700
000100030
001000068
008500010
090000400

程序应该输出:
812753649
943682175
675491283
154237896
369845721
287169534
521974368
438526917
796318452

资源约定:
峰值内存消耗(含虚拟机) < 256M

CPU消耗 < 2000ms

突然发现dfs真神奇,好多题都可以解决。搜索+递归+回溯!哈哈哈

这个题是站在大神的肩膀上做出来的,在他给的思路上进行了完善。

具体算法,代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
public class 数独 {

static int[][] data=new int[][]{
{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,0,0,5,0,0,0,0,9},
{0,0,4,0,0,0,0,3,0},
{0,0,0,0,0,0,7,0,0}
};
static int[][] mark=new int[9][9];
static boolean flag=true;
static boolean ok=false;
static int cnt;
public static void main(String[] args) {

long t1=System.currentTimeMillis();
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if(data[i][j]!=0)
mark[i][j]=1;
}
}
dfs(0,0);
long t2=System.currentTimeMillis();
System.out.println(t2-t1);
}
private static void dfs(int m, int n) {

if(ok==true)
return;

if(m==8&&n==9){
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(data[i][j]+" ");
}
System.out.println();
}
//System.out.println("--------------------------");
ok=true;//true
return;
}
else{
if(n==9){//到了一行的边界
dfs(m+1,0);//跳到下一行
return;
}
if(mark[m][n]==1){//若填过了
dfs(m,n+1);//跳到下一各
return;
}

for (int i = 1; i <= 9; i++) {

aa:for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
//所在行和列都可以填
if(mark[m][y]==1&&data[m][y]==i||
mark[x][n]==1&&data[x][n]==i){
flag=false;
break aa;
}
}
}
//检查所在方阵
if(flag){
int z=m/3;
int v=n/3;
bb:for (int j = 0; j < 3; j++) {
for (int l = 0; l < 3; l++) {
if(mark[z*3+j][v*3+l]==1&&data[z*3+j][v*3+l]==i){
flag=false;
break bb;
}
}
}
}
if(flag==true){
mark[m][n]=1;
data[m][n]=i;
dfs(m,n+1);
mark[m][n]=0;
}
flag=true;
}
}
}
}