Valid Sudoku

Source

Determine whether a Sudoku is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character ..

Example
The following partially filed sudoku is valid.

Valid Sudoku

Note
A valid Sudoku board (partially filled) is not necessarily solvable. Only the filled cells need to be validated.

Clarification
What is Sudoku?

http://sudoku.com.au/TheRules.aspx
https://zh.wikipedia.org/wiki/%E6%95%B8%E7%8D%A8
https://en.wikipedia.org/wiki/Sudoku
http://baike.baidu.com/subview/961/10842669.htm

Python

class Solution:
    # @param board, a 9x9 2D array
    # @return a boolean
    def isValidSudoku(self, board):
        m = len(board)

        for i in range(9):
            row = set()
            col = set()
            cube = set()

            for j in range(9):

                if board[i][j]!='.' and board[i][j] in row:
                    return False
                elif board[i][j] !='.' and board[i][j] not in row:
                    row.add(board[i][j])

                if board[j][i]!='.' and board[j][i] in col:
                    return False
                elif board[j][i] !='.' and board[j][i] not in col:
                    col.add(board[j][i])

                rowIndex=3*(i/3)
                colIndex=3*(i%3)

                if board[rowIndex+j/3][colIndex+j%3]!='.' and board[rowIndex+j/3][colIndex+j%3] in cube:
                    return False
                elif board[rowIndex+j/3][colIndex+j%3]!='.' and board[rowIndex+j/3][colIndex+j%3] not in cube:
                    cube.add(board[rowIndex+j/3][colIndex+j%3])
        return True

Java

class Solution {
    /**
      * @param board: the board
        @return: wether the Sudoku is valid
      */
    public boolean isValidSudoku(char[][] board) {
        if(board==null || board.length==0 || board[0].length==0) return false;

        for(int i=0; i<9; i++){
            HashSet row = new HashSet();
            HashSet col = new HashSet();
            HashSet cube = new HashSet();

            for(int j=0; j<9; j++){
                if(board[i][j]!='.' && !row.add(board[i][j])) return false;

                if(board[j][i]!='.' && !col.add(board[j][i])) return false;

                int rowIndex=3*(i/3);
                int colIndex=3*(i%3);

                if(board[rowIndex+j/3][colIndex+j%3]!='.' && !cube.add(board[rowIndex+j/3][colIndex+j%3])) return false;
            }
        }

        return true;
    }
};