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'.'.
![]()
思路:先全局后局部
public class Solution {
public boolean isValidSudoku(char[][] board) {
// check big board
for (int i=0;i<9;i++){
HashSet<Character> rows = new HashSet<Character>();
HashSet<Character> cols = new HashSet<Character>();
for (int j=0;j<9;j++){
if (board[i][j]!='.'&&!rows.add(board[i][j])){
return false;
}
if (board[j][i]!='.'&&!cols.add(board[j][i])){
return false;
}
}
}
// check cube
for (int i=0;i<3;i++){
for (int j=0;j<3;j++){
HashSet<Character> cubes = new HashSet<Character>();
for (int m=0;m<3;m++){
for (int n=0;n<3;n++){
int rowNum = i*3+m;
int colNum = j*3+n;
if (board[rowNum][colNum]!='.'&&!cubes.add(board[rowNum][colNum])){
return false;
}
}
}
}
}
return true;
}
}