forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ValidSudoku.swift
77 lines (62 loc) · 2.11 KB
/
ValidSudoku.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/**
* Question Link: https://leetcode.com/problems/valid-sudoku/
* Primary idea: Check rows, columns, and single square separately
*
* Time Complexity: O(n^2), Space Complexity: O(n)
*/
class ValidSudoku {
func isValidSudoku(_ board: [[Character]]) -> Bool {
return areRowsValid(board) && areColsValid(board) && areSubsquaresValid(board)
}
private func areRowsValid(_ board: [[Character]]) -> Bool {
var existingDigits = Set<Character>()
for i in 0..<board.count {
existingDigits.removeAll()
for j in 0..<board[0].count {
if !isDigitValid(board[i][j], &existingDigits) {
return false
}
}
}
return true
}
private func areColsValid(_ board: [[Character]]) -> Bool {
var existingDigits = Set<Character>()
for i in 0..<board[0].count {
existingDigits.removeAll()
for j in 0..<board.count {
if !isDigitValid(board[j][i], &existingDigits) {
return false
}
}
}
return true
}
private func areSubsquaresValid(_ board: [[Character]]) -> Bool {
var existingDigits = Set<Character>()
for i in stride(from: 0, to: board.count, by: 3) {
for j in stride(from: 0, to: board[0].count, by: 3) {
existingDigits.removeAll()
for m in i..<i + 3 {
for n in j..<j + 3 {
if !isDigitValid(board[m][n], &existingDigits) {
return false
}
}
}
}
}
return true
}
private func isDigitValid(_ digit: Character, _ set: inout Set<Character>) -> Bool {
if digit == "." {
return true
}
if set.contains(digit) {
return false
} else {
set.insert(digit)
return true
}
}
}