Skip to main content

36 Valid Sudoku

LeetCode 36 Valid Sudoku

Determine if a 9 x 9 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 nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:

  • A Sudoku board (partially filled) could be valid but is not necessarily solvable.
  • Only the filled cells need to be validated according to the mentioned rules.
class Solution {
public boolean isValidSudoku(char[][] board) {
for(int i=0;i<9;++i){
if(!(isRowValid(board,i) && isColValid(board,i))) return false;
}

for(int i=0;i<9;i=i+3){
for(int j=0;j<9;j=j+3){
if(!isBlockValid(board,i,j)) return false;
}
}
return true;
}

private boolean isRowValid(char[][] board, int row){
boolean[] arr=new boolean[9];
for(int j=0;j<9;++j){
char c = board[row][j];
if(c>='1' && c<='9'){
int val = c-'1';
if(arr[val]) return false;
arr[val] = true;
}
}
return true;
}

private boolean isColValid(char[][] board, int col){
boolean[] arr=new boolean[9];
for(int i=0;i<9;++i){
char c = board[i][col];
if(c>='1' && c<='9'){
int val = c-'1';
if(arr[val]) return false;
arr[val] = true;
}
}
return true;
}

private boolean isBlockValid(char[][] board, int i, int j){
int row=i/3*3;
int col=j/3*3;
boolean[] arr=new boolean[9];
for(int ii=0;ii<3;ii++){
for(int jj=0;jj<3;jj++){
char c=board[row+ii][col+jj];
if(c>='1' && c<='9'){
int val = c-'1';
if(arr[val]) return false;
arr[val] = true;
}
}
}
return true;
}
}