@@ -51,37 +51,43 @@ class Solution {
51
51
}
52
52
53
53
54
- func fillGrid (index : Int ,
54
+ func fillGrid (index : Int ,
55
55
board : inout [[Character ]],
56
56
clo : inout [Set <Character >],
57
57
row : inout [Set <Character >],
58
58
block : inout [Set <Character >]) -> Bool {
59
59
guard index < 81 else {
60
60
return true
61
61
}
62
- let x = index % 9
63
- let y = index / 9
64
- if board[y][x] == " ." {
65
- for c in Solution.num {
66
- if ! clo[y].contains (c), ! row[x].contains (c), ! block[x/ 3 + (y/ 3 ) * 3 ].contains (c) {
67
- board[y][x] = c
68
- clo[y].insert (c)
69
- row[x].insert (c)
70
- block[x/ 3 + (y/ 3 ) * 3 ].insert (c)
71
- if fillGrid (index : index + 1 , board : & board, clo : & clo, row : & row, block : & block) {
72
- return true
73
- } else {
74
- clo[y].remove (c)
75
- row[x].remove (c)
76
- block[x/ 3 + (y/ 3 ) * 3 ].remove (c)
77
- board[y][x] = " ."
78
- }
62
+ var i = index
63
+ var x = i % 9
64
+ var y = i / 9
65
+ while board[y][x] != " ." {
66
+ i += 1
67
+ guard i < 81 else {
68
+ return true
69
+ }
70
+ x = i % 9
71
+ y = i / 9
72
+ }
73
+
74
+ for c in Solution.num {
75
+ if ! clo[y].contains (c), ! row[x].contains (c), ! block[x/ 3 + (y/ 3 ) * 3 ].contains (c) {
76
+ board[y][x] = c
77
+ clo[y].insert (c)
78
+ row[x].insert (c)
79
+ block[x/ 3 + (y/ 3 ) * 3 ].insert (c)
80
+ if fillGrid (index : i + 1 , board : & board, clo : & clo, row : & row, block : & block) {
81
+ return true
82
+ } else {
83
+ clo[y].remove (c)
84
+ row[x].remove (c)
85
+ block[x/ 3 + (y/ 3 ) * 3 ].remove (c)
86
+ board[y][x] = " ."
79
87
}
80
88
}
81
- return false
82
- } else {
83
- return fillGrid (index : index + 1 , board : & board, clo : & clo, row : & row, block : & block)
84
89
}
90
+ return false
85
91
}
86
92
}
87
93
@@ -98,8 +104,8 @@ class Solution {
98
104
var row = [Set < Character > ].init (repeating : Set < Character > (), count : 9 )
99
105
var block = [Set < Character > ].init (repeating : Set < Character > (), count : 9 )
100
106
var points = [(p : (x : Int , y : Int ), c : Int )]()
107
+ var points = [(p : (x : Int , y : Int ), c : Int )]()
101
108
for y in 0 ..< 9 {
102
- for x in 0 ..< 9 {
103
109
let c = board[y][x]
104
110
guard c != " ." else {
105
111
points.append ((p : (x : x, y : y), c : 0 ))
@@ -157,3 +163,20 @@ class Solution {
157
163
}
158
164
159
165
```
166
+
167
+ ```
168
+ 对于测试数组
169
+ [["5","3",".",".","7",".",".",".","."],
170
+ ["6",".",".","1","9","5",".",".","."],
171
+ [".","9","8",".",".",".",".","6","."],
172
+ ["8",".",".",".","6",".",".",".","3"],
173
+ ["4",".",".","8",".","3",".",".","1"],
174
+ ["7",".",".",".","2",".",".",".","6"],
175
+ [".","6",".",".",".",".","2","8","."],
176
+ [".",".",".","4","1","9",".",".","5"],
177
+ [".",".",".",".","8",".",".","7","9"]]
178
+
179
+ 扫描遍历尝试填充4208次,按权重遍历调用fillGrid 340次
180
+
181
+ ```
182
+
0 commit comments