LeetCode #36 Valid Sudoku
Question
Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
A partially filled sudoku which is valid.
Note:
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.
Solution
Approach #1
class Solution {
func isValidSudoku(_ board: [[Character]]) -> Bool {
for i in 0..<9 {
var rowCharSet = Set<Character>()
var colCharSet = Set<Character>()
var cellCharSet = Set<Character>()
let point: Character = "."
for j in 0..<9 {
if board[i][j] != point {
if rowCharSet.contains(board[i][j]) { return false }
rowCharSet.insert(board[i][j])
}
if board[j][i] != "." {
if colCharSet.contains(board[j][i]) { return false }
colCharSet.insert(board[j][i])
}
let p = i / 3 * 3 + j / 3
let q = i % 3 * 3 + j % 3
if board[p][q] != "." {
if cellCharSet.contains(board[p][q]) { return false }
cellCharSet.insert(board[p][q])
}
}
}
return true
}
}
转载请注明出处:http://www.cnblogs.com/silence-cnblogs/p/7074614.html