36. Valid Sudoku
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 ‘.’.
方法
本题实际上一共分为3种情况:按行,按列,按3 * 3块。对于3 * 3块,使用从左往右,从上往下的方式扫描。行列块分别用3个HashSet进行存放,若其hashSet有新插入的值,则返回false。
public class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i = 0; i < board.length; i++){
HashSet<Character> row = new HashSet<Character>();
HashSet<Character> col = new HashSet<Character>();
HashSet<Character> cube = new HashSet<Character>();
for(int j = 0; j < board[0].length; 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;
}
}