Skip to content

Commit 689449e

Browse files
aQuaaQua
aQua
authored and
aQua
committed
adding Problem 37
按照网上的算法,编写了一个答案,但是不能通过单元测试。
1 parent e4f00e6 commit 689449e

File tree

2 files changed

+65
-13
lines changed

2 files changed

+65
-13
lines changed
Lines changed: 54 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,62 @@
11
package Problem0037
22

33
func solveSudoku(board [][]byte) {
4-
res := [][]byte{
5-
[]byte("519748632"),
6-
[]byte("783652419"),
7-
[]byte("426139875"),
8-
[]byte("357986241"),
9-
[]byte("264317598"),
10-
[]byte("198524367"),
11-
[]byte("975863124"),
12-
[]byte("832491756"),
13-
[]byte("641275983"),
4+
nums := []byte("519783426")
5+
for _, n := range nums {
6+
if !fillBlock(board, n, 0) {
7+
panic("此题无解")
8+
}
9+
}
10+
}
11+
12+
func fillBlock(board [][]byte, n byte, block int) bool {
13+
print(board, n, block)
14+
15+
if block == 9 {
16+
return true
17+
}
18+
19+
rowZero := (block / 3) * 3
20+
colZero := (block % 3) * 3
21+
22+
// 检查block中,是否已经存在 b 了
23+
had := func() bool {
24+
for r := rowZero; r < rowZero+3; r++ {
25+
for c := colZero; c < colZero+3; c++ {
26+
if board[r][c] == n {
27+
return true
28+
}
29+
}
30+
}
31+
return false
1432
}
1533

16-
for i, v := range board {
17-
for j := range v {
18-
board[i][j] = res[i][j]
34+
if had() {
35+
return fillBlock(board, n, block+1)
36+
}
37+
// 检查(r,c)所在的行和列是否已经存在 b 了
38+
isClear := func(r, c int) bool {
39+
for i := 0; i < 9; i++ {
40+
if board[r][i] == n || board[i][c] == n {
41+
return false
42+
}
1943
}
44+
return true
2045
}
46+
47+
for r := rowZero; r < rowZero+3; r++ {
48+
for c := colZero; c < colZero+3; c++ {
49+
if board[r][c] == '.' && isClear(r, c) {
50+
board[r][c] = n
51+
if fillBlock(board, n, block+1) {
52+
return true
53+
}
54+
// 后面的填写不成功,所以需要还原这个格子
55+
board[r][c] = '.'
56+
print(board, n, block)
57+
}
58+
}
59+
}
60+
61+
return false
2162
}

Algorithms/0037.sudoku-solver/sudoku-solver_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,3 +64,14 @@ func Test_Problem0036(t *testing.T) {
6464
ast.Equal(a.one, p.one, "输入:%v", p)
6565
}
6666
}
67+
68+
func print(board [][]byte, b byte, block int) {
69+
fmt.Printf("\n====fill %d in block %d ====", b-'0', block)
70+
71+
for i := range board {
72+
if i%3 == 0 {
73+
fmt.Println()
74+
}
75+
fmt.Println(string(board[i][0:3]), " ", string(board[i][3:6]), " ", string(board[i][6:]))
76+
}
77+
}

0 commit comments

Comments
 (0)