forked from soapyigu/LeetCode-Swift
-
Notifications
You must be signed in to change notification settings - Fork 1
/
ValidSudoku.swift
81 lines (67 loc) · 2.28 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
78
79
80
81
/**
* 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 {
let size = 9
func isValidSudoku(board: [[Character]]) -> Bool {
return _isRowValid(board) && _isColValid(board) && _isSquareValid(board)
}
private func _isRowValid(board: [[Character]]) -> Bool {
var visited = Array(count: size, repeatedValue: false)
for i in 0 ..< size {
visited = Array(count: size, repeatedValue: false)
for j in 0 ..< size {
if !_isValidChar(board[i][j], &visited) {
return false
}
}
}
return true
}
private func _isColValid(board: [[Character]]) -> Bool {
var visited = Array(count: size, repeatedValue: false)
for i in 0 ..< size {
visited = Array(count: size, repeatedValue: false)
for j in 0 ..< size {
if !_isValidChar(board[j][i], &visited) {
return false
}
}
}
return true
}
private func _isSquareValid(board: [[Character]]) -> Bool {
var visited = Array(count: size, repeatedValue: false)
for i in 0.stride(to: size, by: 3) {
for j in 0.stride(to: size, by: 3) {
visited = Array(count: size, repeatedValue: false)
for m in i ..< i + 3 {
for n in j ..< j + 3 {
if !_isValidChar(board[m][n], &visited) {
return false
}
}
}
}
}
return true
}
private func _isValidChar(char: Character, inout _ visited: [Bool]) -> Bool {
let current = String(char)
if current != "." {
if let num = Int(current){
if num < 1 || num > 9 || visited[num - 1] {
return false
} else {
visited[num - 1] = true
}
} else {
return false
}
}
return true
}
}