|
| 1 | +// https://leetcode.com/problems/valid-sudoku |
| 2 | +// T: O(1) |
| 3 | +// S: O(1) |
| 4 | + |
| 5 | +import java.util.HashSet; |
| 6 | +import java.util.Set; |
| 7 | + |
| 8 | +public class ValidSudoku { |
| 9 | + private static final int SUDOKU_SIZE = 9; |
| 10 | + |
| 11 | + public boolean isValidSudoku(char[][] board) { |
| 12 | + if (repetitionInRows(board)) return false; |
| 13 | + if (repetitionInColumns(board)) return false; |
| 14 | + return !repetitionInBlocks(board); |
| 15 | + } |
| 16 | + |
| 17 | + private boolean repetitionInRows(char[][] board) { |
| 18 | + for (char[] row : board) { |
| 19 | + if (repetitionInRow(row)) return true; |
| 20 | + } |
| 21 | + return false; |
| 22 | + } |
| 23 | + |
| 24 | + private boolean repetitionInRow(char[] row) { |
| 25 | + final Set<Character> digits = new HashSet<>(); |
| 26 | + for (char character : row) { |
| 27 | + if (Character.isDigit(character)) { |
| 28 | + if (digits.contains(character)) return true; |
| 29 | + digits.add(character); |
| 30 | + } |
| 31 | + } |
| 32 | + return false; |
| 33 | + } |
| 34 | + |
| 35 | + private boolean repetitionInColumns(char[][] board) { |
| 36 | + final Set<Character> digits = new HashSet<>(); |
| 37 | + for (int column = 0 ; column < SUDOKU_SIZE ; column++) { |
| 38 | + digits.clear(); |
| 39 | + for (int row = 0 ; row < SUDOKU_SIZE ; row++) { |
| 40 | + char c = board[row][column]; |
| 41 | + if (Character.isDigit(c)) { |
| 42 | + if (digits.contains(c)) return true; |
| 43 | + digits.add(c); |
| 44 | + } |
| 45 | + } |
| 46 | + } |
| 47 | + return false; |
| 48 | + } |
| 49 | + |
| 50 | + private boolean repetitionInBlocks(char[][] board) { |
| 51 | + for (int i = 0 ; i < SUDOKU_SIZE / 3 ; i++) { |
| 52 | + for (int j = 0 ; j < SUDOKU_SIZE / 3 ; j++) { |
| 53 | + if (repetitionInBlock(board, i, j)) return true; |
| 54 | + } |
| 55 | + } |
| 56 | + return false; |
| 57 | + } |
| 58 | + |
| 59 | + private boolean repetitionInBlock(final char[][] board, final int i, final int j) { |
| 60 | + final Set<Character> digits = new HashSet<>(); |
| 61 | + for (int row = 3 * i ; row < 3 * i + 3 ; row++) { |
| 62 | + for (int column = 3 * j ; column < 3 * j + 3 ; column++) { |
| 63 | + char c = board[row][column]; |
| 64 | + if (Character.isDigit(c)) { |
| 65 | + if (digits.contains(c)) return true; |
| 66 | + digits.add(c); |
| 67 | + } |
| 68 | + } |
| 69 | + } |
| 70 | + return false; |
| 71 | + } |
| 72 | +} |
0 commit comments