@@ -27,6 +27,7 @@ A sudoku puzzle...
27
27
28
28
#Solution
29
29
30
+ 扫描遍历
30
31
``` swift
31
32
32
33
class Solution {
@@ -85,3 +86,74 @@ class Solution {
85
86
}
86
87
87
88
```
89
+
90
+
91
+ 按照权重遍历
92
+ ``` swift
93
+
94
+ class Solution {
95
+ static let num: [Character ]= [" 1" ," 2" ," 3" ," 4" ," 5" ," 6" ," 7" ," 8" ," 9" ]
96
+ func solveSudoku (_ board :inout [[Character ]]) {
97
+ var clo= [Set < Character > ].init (repeating :Set < Character > (),count :9 )
98
+ var row= [Set < Character > ].init (repeating :Set < Character > (),count :9 )
99
+ var block= [Set < Character > ].init (repeating :Set < Character > (),count :9 )
100
+ var points= [(p : (x :Int ,y :Int ),c :Int )]()
101
+ for yin 0 ..< 9 {
102
+ for xin 0 ..< 9 {
103
+ let c= board[y][x]
104
+ guard c!= " ." else {
105
+ points.append ((p : (x : x,y : y),c :0 ))
106
+ continue
107
+ }
108
+ clo[y].insert (c)
109
+ row[x].insert (c)
110
+ block[x/ 3 + (y/ 3 )* 3 ].insert (c)
111
+ }
112
+ }
113
+ let _clo= clo.map ({$0 .count })
114
+ let _row= row.map ({$0 .count })
115
+ let _block= block.map ({$0 .count })
116
+ for iin 0 ..< points.count {
117
+ let (x, y)= points[i].p
118
+ points[i].c = _clo[y]+ _row[x]+ _block[x/ 3 + (y/ 3 )* 3 ]
119
+ }
120
+ _ = fillGrid (index :0 ,
121
+ point : points.sorted (by : {$0 .c > $1 .c }).map ({$0 .p }),
122
+ board :& board,
123
+ clo :& clo,
124
+ row :& row,
125
+ block :& block)
126
+ }
127
+
128
+
129
+ func fillGrid (index :Int ,
130
+ point : [(x:Int , y:Int )],
131
+ board :inout [[Character ]],
132
+ clo :inout [Set <Character >],
133
+ row :inout [Set <Character >],
134
+ block :inout [Set <Character >])-> Bool {
135
+ if index== point.count {
136
+ return true
137
+ }
138
+ let (x, y)= point[index]
139
+ for cin Solution.num {
140
+ if ! clo[y].contains (c),! row[x].contains (c),! block[x/ 3 + (y/ 3 )* 3 ].contains (c) {
141
+ board[y][x]= c
142
+ clo[y].insert (c)
143
+ row[x].insert (c)
144
+ block[x/ 3 + (y/ 3 )* 3 ].insert (c)
145
+ if fillGrid (index : index+ 1 ,point : point,board :& board,clo :& clo,row :& row,block :& block) {
146
+ return true
147
+ }else {
148
+ clo[y].remove (c)
149
+ row[x].remove (c)
150
+ block[x/ 3 + (y/ 3 )* 3 ].remove (c)
151
+ board[y][x]= " ."
152
+ }
153
+ }
154
+ }
155
+ return false
156
+ }
157
+ }
158
+
159
+ ```