|
| 1 | +import java.util.*; |
| 2 | + |
| 3 | +class Solution { |
| 4 | + public boolean isValidSudoku(char[][] board) { |
| 5 | + final int size = 9; |
| 6 | + |
| 7 | + if (board == null || board.length != size || board[0].length != size) { |
| 8 | + return false; |
| 9 | + } |
| 10 | + |
| 11 | + ArrayList<HashSet<Character>> row = new ArrayList<HashSet<Character>>(); |
| 12 | + ArrayList<HashSet<Character>> col = new ArrayList<HashSet<Character>>(); |
| 13 | + ArrayList<HashSet<Character>> area = new ArrayList<HashSet<Character>>(); |
| 14 | + |
| 15 | + for (int i = 0; i < size; i++) { |
| 16 | + row.add(new HashSet<Character>()); |
| 17 | + col.add(new HashSet<Character>()); |
| 18 | + area.add(new HashSet<Character>()); |
| 19 | + } |
| 20 | + |
| 21 | + for (int i = 0; i < size; i++) { // row |
| 22 | + for (int j = 0; j < size; j++) { // column |
| 23 | + int box = 3 * (i / 3) + j / 3; // sub box |
| 24 | + if (board[i][j] != '.') { |
| 25 | + if (row.get(i).contains(board[i][j]) |
| 26 | + || col.get(j).contains(board[i][j]) |
| 27 | + || area.get(box).contains(board[i][j])) { |
| 28 | + return false; |
| 29 | + } |
| 30 | + row.get(i).add(board[i][j]); |
| 31 | + col.get(j).add(board[i][j]); |
| 32 | + area.get(box).add(board[i][j]); |
| 33 | + } |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return true; |
| 38 | + } |
| 39 | + |
| 40 | + public static void main(String[] args) { |
| 41 | + Solution solution = new Solution(); |
| 42 | + char[][] board = { |
| 43 | + {'.','8','7','6','5','4','3','2','1'}, |
| 44 | + {'2','.','.','.','.','.','.','.','.'}, |
| 45 | + {'3','.','.','.','.','.','.','.','.'}, |
| 46 | + {'4','.','.','.','.','.','.','.','.'}, |
| 47 | + {'5','.','.','.','.','.','.','.','.'}, |
| 48 | + {'6','.','.','.','.','.','.','.','.'}, |
| 49 | + {'7','.','.','.','.','.','.','.','.'}, |
| 50 | + {'8','.','.','.','.','.','.','.','.'}, |
| 51 | + {'9','.','.','.','.','.','.','.','.'} |
| 52 | + }; |
| 53 | + |
| 54 | + System.out.println(solution.isValidSudoku(board)); |
| 55 | + } |
| 56 | +} |
0 commit comments