Valid Sudoku

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.

class Solution {
    func isValidSudoku(_ board: [[Character]]) -> Bool {
        for i in 0 ... 8 {
            var rowSet = Set()
            var colSet = Set()
            var subBoxSet = Set()
            let rowStart = (i / 3) * 3;
            let colStart = (i % 3) * 3;

            for j in 0 ... 8 {
                if board[i][j] != "." {
                    if rowSet.contains(board[i][j]) {
                        return false
                    } else {
                        rowSet.insert(board[i][j])
                    }
                }

                if board[j][i] != "." {
                    if colSet.contains(board[j][i]) {
                        return false
                    } else {
                        colSet.insert(board[j][i])
                    }
                }

                if board[rowStart + j / 3][colStart + j % 3] != "." {
                    if subBoxSet.contains(board[rowStart + j / 3][colStart + j % 3]) {
                        return false
                    } else {
                        subBoxSet.insert(board[rowStart + j / 3][colStart + j % 3])
                    }
                }

            }
        }
        return true
    }
}

你可能感兴趣的:(Valid Sudoku)