-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0036.Valid Sudoku.swift
76 lines (68 loc) · 1.94 KB
/
0036.Valid Sudoku.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
class Solution {
private var board = [[Character]]()
func isValidSudoku(_ board: [[Character]]) -> Bool {
self.board = board
for r in 0..<9 {
if !isValid(row: r) {
return false
}
}
for c in 0..<9 {
if !isValid(col: c) {
return false
}
}
for r in 0..<3 {
for c in 0..<3 {
if !isValidBox(r*3, c*3) {
return false
}
}
}
return true
}
private func isValid(row: Int) -> Bool {
var seen = Array(repeating: false, count: 9)
for c in 0..<9 {
let ch = board[row][c]
if ch != "." {
if seen[ch.wholeNumberValue! - 1] {
return false
} else {
seen[ch.wholeNumberValue! - 1] = true
}
}
}
return true
}
private func isValid(col: Int) -> Bool {
var seen = Array(repeating: false, count: 9)
for r in 0..<9 {
let ch = board[r][col]
if ch != "." {
if seen[ch.wholeNumberValue! - 1] {
return false
} else {
seen[ch.wholeNumberValue! - 1] = true
}
}
}
return true
}
private func isValidBox(_ row: Int, _ col: Int) -> Bool {
var seen = Array(repeating: false, count: 9)
for r in row..<row+3 {
for c in col..<col+3 {
let ch = board[r][c]
if ch != "." {
if seen[ch.wholeNumberValue! - 1] {
return false
} else {
seen[ch.wholeNumberValue! - 1] = true
}
}
}
}
return true
}
}