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.
题目含义:数独板被部分填充,空格部分用'.'来填充。 一个部分填充的数组是否有效只需要看其填充的部分即可
一个数独合法的标准如下
-
每一行每一列必须包含1-9之间的每一个数字(包括1和9)
-
每一个小的正方形矩阵中必须包含1-9之间的每一个数字(包括1和9)
1 public boolean isValidSudoku(char[][] board) { 2 for(int i = 0; i<9; i++){ 3 HashSet<Character> rows = new HashSet<Character>(); 4 HashSet<Character> columns = new HashSet<Character>(); 5 HashSet<Character> cube = new HashSet<Character>(); 6 for (int j = 0; j < 9;j++){ 7 if(board[i][j]!='.' && !rows.add(board[i][j])) 8 return false; 9 if(board[j][i]!='.' && !columns.add(board[j][i])) 10 return false; 11 12 //计算当前小方格所在的正方形 13 int RowIndex = 3*(i/3); 14 int ColIndex = 3*(i%3); 15 if(board[RowIndex + j/3][ColIndex + j%3]!='.' && !cube.add(board[RowIndex + j/3][ColIndex + j%3])) 16 return false; 17 } 18 } 19 return true; 20 }