Skip to content

Commit 9c24227

Browse files
author
Yi Gu
committed
Update the solution to the Valid Sudoku
1 parent fae043e commit 9c24227

File tree

1 file changed

+28
-52
lines changed

1 file changed

+28
-52
lines changed

Array/ValidSudoku.swift

Lines changed: 28 additions & 52 deletions
Original file line numberDiff line numberDiff line change
@@ -6,71 +6,47 @@
66
*/
77

88
class ValidSudoku {
9-
func isValidSudoku(_ board: [[Character]]) -> Bool {
10-
return areRowsValid(board) && areColsValid(board) && areSubsquaresValid(board)
11-
}
12-
13-
private func areRowsValid(_ board: [[Character]]) -> Bool {
14-
var existingDigits = Set<Character>()
15-
16-
for i in 0..<board.count {
17-
existingDigits.removeAll()
18-
19-
for j in 0..<board[0].count {
20-
if !isDigitValid(board[i][j], &existingDigits) {
21-
return false
22-
}
23-
}
24-
}
9+
func isValidSudoku(_ board: [[Character]]) -> Bool {
10+
let len = 9
2511

26-
return true
27-
}
28-
29-
private func areColsValid(_ board: [[Character]]) -> Bool {
30-
var existingDigits = Set<Character>()
12+
var rowSet = Array(repeating: Set<Character>(), count: len)
13+
var colSet = Array(repeating: Set<Character>(), count: len)
14+
var boxSet = Array(repeating: Set<Character>(), count: len)
3115

32-
for i in 0..<board[0].count {
33-
existingDigits.removeAll()
34-
35-
for j in 0..<board.count {
36-
if !isDigitValid(board[j][i], &existingDigits) {
37-
return false
16+
for i in 0..<len {
17+
for j in 0..<len {
18+
let currentChar = board[i][j]
19+
20+
if currentChar == "." {
21+
continue
22+
}
23+
24+
// check row
25+
if !isValid(&rowSet[i], currentChar) {
26+
return false
27+
}
28+
29+
// check column
30+
if !isValid(&colSet[j], currentChar) {
31+
return false
3832
}
39-
}
40-
}
41-
42-
return true
43-
}
44-
45-
private func areSubsquaresValid(_ board: [[Character]]) -> Bool {
46-
var existingDigits = Set<Character>()
47-
48-
for i in stride(from: 0, to: board.count, by: 3) {
49-
for j in stride(from: 0, to: board[0].count, by: 3) {
50-
existingDigits.removeAll()
5133

52-
for m in i..<i + 3 {
53-
for n in j..<j + 3 {
54-
if !isDigitValid(board[m][n], &existingDigits) {
55-
return false
56-
}
57-
}
34+
// check sub-box
35+
let idx = 3 * (i / 3) + j / 3
36+
if !isValid(&boxSet[idx], currentChar) {
37+
return false
5838
}
5939
}
6040
}
6141

6242
return true
6343
}
6444

65-
private func isDigitValid(_ digit: Character, _ set: inout Set<Character>) -> Bool {
66-
if digit == "." {
67-
return true
68-
}
69-
70-
if set.contains(digit) {
45+
private func isValid(_ set: inout Set<Character>, _ char: Character) -> Bool {
46+
if set.contains(char) {
7147
return false
7248
} else {
73-
set.insert(digit)
49+
set.insert(char)
7450
return true
7551
}
7652
}

0 commit comments

Comments
 (0)