LeetCode – 36. Valid Sudoku

題目連結: https://leetcode.com/problems/valid-sudoku/

func isValidSudoku(_ board: [[Character]]) -> Bool {
    for i in 0 ..< 9 {
        var rowSet: Set<Character> = []
        var colSet: Set<Character> = []
        for j in 0 ..< 9 {
            if board[i][j] != "." {
                let (inserted1, _) = colSet.insert(board[i][j])
                if !inserted1 {
                    return false
                }
            }
            if board[j][i] != "." {
                let (inserted2, _) = rowSet.insert(board[j][i])
                if !inserted2 {
                    return false
                }
            }
        }
    }

    for i in 0 ..< 3 {
        for j in 0 ..< 3 {
            var set: Set<Character> = []
            for k in 0 ..< 3 {
                for l in 0 ..< 3 {
                    let x = i*3 + k
                    let y = j*3 + l
                    if board[x][y] != "." {
                          let (inserted, _) = set.insert(board[x][y])
                          if !inserted {
                              return false
                          }
                      }
                }
            }
        }
    }
    return true
}