36 Valid Sudoku
Description
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.
Hint
hashmap
Method
- three sets to check row col cube
- one set to check all using string
Time & Space
o(n^2)
s: o(n)
Code
public boolean isValidSudoku(char[][] board) {
if (board == null || board.length == 0){
return false;
}
HashSet<String> set = new HashSet<String>();
for (int i = 0; i < 9; i++){
for (int j = 0; j < 9; j++){
if (board[i][j] != '.'){
String s = "(" + board[i][j] + ")";
if (!set.add(i + s) || !set.add(s + j) || !set.add(i/ 3 + s + j / 3)){
return false;
}
}
}
}
return true;
}