@@ -51,37 +51,43 @@ class Solution {
5151 }
5252
5353
54- func fillGrid (index : Int ,
54+ func fillGrid (index : Int ,
5555 board : inout [[Character ]],
5656 clo : inout [Set <Character >],
5757 row : inout [Set <Character >],
5858 block : inout [Set <Character >]) -> Bool {
5959 guard index < 81 else {
6060 return true
6161 }
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] = " ."
7987 }
8088 }
81- return false
82- } else {
83- return fillGrid (index : index + 1 , board : & board, clo : & clo, row : & row, block : & block)
8489 }
90+ return false
8591 }
8692}
8793
@@ -98,8 +104,8 @@ class Solution {
98104 var row = [Set < Character > ].init (repeating : Set < Character > (), count : 9 )
99105 var block = [Set < Character > ].init (repeating : Set < Character > (), count : 9 )
100106 var points = [(p : (x : Int , y : Int ), c : Int )]()
107+ var points = [(p : (x : Int , y : Int ), c : Int )]()
101108 for y in 0 ..< 9 {
102- for x in 0 ..< 9 {
103109 let c = board[y][x]
104110 guard c != " ." else {
105111 points.append ((p : (x : x, y : y), c : 0 ))
@@ -157,3 +163,20 @@ class Solution {
157163}
158164
159165```
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