@@ -2,22 +2,26 @@ package Problem0037
2
2
3
3
func solveSudoku (board [][]byte ) {
4
4
nums := []byte ("123456789" )
5
- blocks := []int {1 , 3 , 5 , 7 , 0 , 8 , 4 , 2 , 6 }
6
- for _ , n := range nums {
7
- if ! fillBlock (board , n , blocks ) {
8
- panic ("此题无解" )
9
- }
5
+ blocks := []int {0 , 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 }
6
+
7
+ if ! fillBlock (board , nums , blocks ) {
8
+ panic ("此题无解" )
10
9
}
11
10
}
12
11
13
- func fillBlock (board [][]byte , n byte , blocks []int ) bool {
12
+ func fillBlock (board [][]byte , nums [] byte , blocks []int ) bool {
14
13
if len (blocks ) == 0 {
15
14
return true
16
15
}
16
+ if len (nums ) == 0 {
17
+ return fillBlock (board , []byte ("123456789" ), blocks [1 :])
18
+ }
17
19
18
20
block := blocks [0 ]
21
+ n := nums [0 ]
22
+ nums = nums [1 :]
19
23
20
- print (board , n , block )
24
+ // print(board, n, block)
21
25
22
26
rowZero := (block / 3 ) * 3
23
27
colZero := (block % 3 ) * 3
@@ -35,9 +39,9 @@ func fillBlock(board [][]byte, n byte, blocks []int) bool {
35
39
}
36
40
37
41
if had () {
38
- return fillBlock (board , n , blocks [ 1 :] )
42
+ return fillBlock (board , nums , blocks )
39
43
}
40
- // 检查(r,c)所在的行和列是否已经存在 b 了
44
+ // 检查(r,c)所在的行和列是否已经存在 n 了
41
45
isClear := func (r , c int ) bool {
42
46
for i := 0 ; i < 9 ; i ++ {
43
47
if board [r ][i ] == n || board [i ][c ] == n {
@@ -51,12 +55,12 @@ func fillBlock(board [][]byte, n byte, blocks []int) bool {
51
55
for c := colZero ; c < colZero + 3 ; c ++ {
52
56
if board [r ][c ] == '.' && isClear (r , c ) {
53
57
board [r ][c ] = n
54
- if fillBlock (board , n , blocks [ 1 :] ) {
58
+ if fillBlock (board , nums , blocks ) {
55
59
return true
56
60
}
57
61
// 后面的填写不成功,所以需要还原这个格子
58
62
board [r ][c ] = '.'
59
- print (board , n , block )
63
+ // print(board, n, block)
60
64
}
61
65
}
62
66
}
0 commit comments