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.
本题是比较有趣的一道题,查看数独是否为有效的valid,难点在于正方形的判断的坐标上,代码如下:
1 public class Solution { 2 public boolean isValidSudoku(char[][] board) { 3 for(int i=0;i<9;i++){ 4 Set<Character> row = new HashSet<Character>(); 5 Set<Character> col = new HashSet<Character>(); 6 Set<Character> dia = new HashSet<Character>(); 7 for(int j=0;j<9;j++){ 8 if(board[i][j]!='.'&&row.contains(board[i][j])){ 9 return false; 10 }else{ 11 row.add(board[i][j]); 12 } 13 if(board[j][i]!='.'&&col.contains(board[j][i])){ 14 return false; 15 }else{ 16 col.add(board[j][i]); 17 } 18 if(board[i/3*3+j/3][i%3*3+j%3]!='.'&&dia.contains(board[i/3*3+j/3][i%3*3+j%3])){ 19 return false; 20 }else{ 21 dia.add(board[i/3*3+j/3][i%3*3+j%3]); 22 } 23 } 24 } 25 return true; 26 } 27 }