Skip to content
This repository was archived by the owner on Apr 27, 2025. It is now read-only.

Commit afd92a5

Browse files
authored
Update 37. Sudoku Solver.md
1 parent 7da23f9 commit afd92a5

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
class Solution {
@@ -85,3 +86,74 @@ class Solution {
8586
}
8687

8788
```
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 y in 0..<9 {
102+
for x in 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 i in 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 c in 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+
```

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy