[LC] 36. Valid Sudoku
Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:
- Each row must contain the digits
1-9
without repetition. - Each column must contain the digits
1-9
without repetition. - Each of the 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
class Solution { public boolean isValidSudoku(char[][] board) { int n = board.length; for (int i = 0; i < n; i++) { SetrowSet = new HashSet<>(); Set colSet = new HashSet<>(); Set cubeSet = new HashSet<>(); for (int j = 0; j < n; j++) { if (board[i][j] != '.' && !rowSet.add(board[i][j])) { return false; } if (board[j][i] != '.' && !colSet.add(board[j][i])) { return false; } int rowIndex = 3 * (i / 3); int colIndex = 3 * (i % 3); if (board[rowIndex + j / 3][colIndex + j % 3] != '.' && !cubeSet.add(board[rowIndex + j / 3][colIndex + j % 3])) { return false; } } } return true; } }