Skip to content

Commit 34db7b2

Browse files
aQuaaQua
aQua
authored and
aQua
committed
adding Problem 37
通过leetcode的测试
1 parent 69791b5 commit 34db7b2

File tree

2 files changed

+17
-12
lines changed

2 files changed

+17
-12
lines changed

Algorithms/0037.sudoku-solver/README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,8 @@ A sudoku puzzle...
1616
...and its solution numbers marked in red.
1717

1818
## 解题思路
19-
19+
我把数独框中,需要保证数字不重复的3×3小块,称为一个block。
20+
由于数独需要保持每行,每列,每个block中的数字不重复。
2021

2122
## 总结
2223

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

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -2,22 +2,26 @@ package Problem0037
22

33
func solveSudoku(board [][]byte) {
44
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("此题无解")
109
}
1110
}
1211

13-
func fillBlock(board [][]byte, n byte, blocks []int) bool {
12+
func fillBlock(board [][]byte, nums []byte, blocks []int) bool {
1413
if len(blocks) == 0 {
1514
return true
1615
}
16+
if len(nums) == 0 {
17+
return fillBlock(board, []byte("123456789"), blocks[1:])
18+
}
1719

1820
block := blocks[0]
21+
n := nums[0]
22+
nums = nums[1:]
1923

20-
print(board, n, block)
24+
// print(board, n, block)
2125

2226
rowZero := (block / 3) * 3
2327
colZero := (block % 3) * 3
@@ -35,9 +39,9 @@ func fillBlock(board [][]byte, n byte, blocks []int) bool {
3539
}
3640

3741
if had() {
38-
return fillBlock(board, n, blocks[1:])
42+
return fillBlock(board, nums, blocks)
3943
}
40-
// 检查(r,c)所在的行和列是否已经存在 b
44+
// 检查(r,c)所在的行和列是否已经存在 n
4145
isClear := func(r, c int) bool {
4246
for i := 0; i < 9; i++ {
4347
if board[r][i] == n || board[i][c] == n {
@@ -51,12 +55,12 @@ func fillBlock(board [][]byte, n byte, blocks []int) bool {
5155
for c := colZero; c < colZero+3; c++ {
5256
if board[r][c] == '.' && isClear(r, c) {
5357
board[r][c] = n
54-
if fillBlock(board, n, blocks[1:]) {
58+
if fillBlock(board, nums, blocks) {
5559
return true
5660
}
5761
// 后面的填写不成功,所以需要还原这个格子
5862
board[r][c] = '.'
59-
print(board, n, block)
63+
// print(board, n, block)
6064
}
6165
}
6266
}

0 commit comments

Comments
 (0)