Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commitafd92a5

Browse files
authored
Update 37. Sudoku Solver.md
1 parent7da23f9 commitafd92a5

File tree

1 file changed

+72
-0
lines changed

1 file changed

+72
-0
lines changed

‎37. Sudoku Solver.md

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ A sudoku puzzle...
2727

2828
#Solution
2929

30+
扫描遍历
3031
```swift
3132

3233
classSolution {
@@ -85,3 +86,74 @@ class Solution {
8586
}
8687

8788
```
89+
90+
91+
按照权重遍历
92+
```swift
93+
94+
classSolution {
95+
staticlet num: [Character]= ["1","2","3","4","5","6","7","8","9"]
96+
funcsolveSudoku(_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 yin0..<9 {
102+
for xin0..<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 iin0..<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+
funcfillGrid(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+
returntrue
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+
iffillGrid(index: index+1,point: point,board:&board,clo:&clo,row:&row,block:&block) {
146+
returntrue
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+
returnfalse
156+
}
157+
}
158+
159+
```

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp