暴力解决。
1 public boolean isValidSudoku(char[][] board) { 2 if(board == null || board.length == 0) { 3 return false; 4 } 5 for(int i = 0; i < 9; i += 3) { 6 for(int j = 0; j < 9; j += 3) { 7 boolean temp = checkSquare(board, i, j); 8 if(temp == false) { 9 return false; 10 } 11 } 12 } 13 for(int i = 0; i < 9; i++) { 14 boolean temp = checkCol(board, i); 15 if(temp == false) { 16 return false; 17 } 18 temp = checkRow(board, i); 19 if(temp == false) { 20 return false; 21 } 22 } 23 return true; 24 } 25 26 private boolean checkCol(char[][] board, int col) { 27 HashSet<Character> set = new HashSet<Character>(); 28 for(int i = 0; i < 9; i++) { 29 char x = board[i][col]; 30 if(x != ‘.‘) { 31 if(set.contains(x)) { 32 return false; 33 } else { 34 set.add(x); 35 } 36 } 37 } 38 return true; 39 } 40 41 private boolean checkRow(char[][] board, int row) { 42 HashSet<Character> set = new HashSet<Character>(); 43 for(int i = 0; i < 9; i++) { 44 char x = board[row][i]; 45 if(x != ‘.‘) { 46 if(set.contains(x)) { 47 return false; 48 } else { 49 set.add(x); 50 } 51 } 52 } 53 return true; 54 } 55 56 private boolean checkSquare(char[][] board, int row, int col) { 57 HashSet<Character> set = new HashSet<Character>(); 58 for(int i = row; i < row + 3; i++) { 59 for(int j = col; j < col + 3; j++) { 60 char x = board[i][j]; 61 if(x != ‘.‘) { 62 if(set.contains(x)) { 63 return false; 64 } else { 65 set.add(x); 66 } 67 } 68 } 69 } 70 return true; 71 }
原文:http://www.cnblogs.com/warmland/p/5222214.html