L36. Valid Sudoku

recursion

Problem:

Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

  1. Each row must contain the digits 1-9 without repetition.

  2. Each column must contain the digits 1-9 without repetition.

  3. Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition.

A partially filled sudoku which is valid.

The Sudoku board could be partially filled, where empty cells are filled with the character '.'.

Example 1:

Input:
[
  ["5","3",".",".","7",".",".",".","."],
  ["6",".",".","1","9","5",".",".","."],
  [".","9","8",".",".",".",".","6","."],
  ["8",".",".",".","6",".",".",".","3"],
  ["4",".",".","8",".","3",".",".","1"],
  ["7",".",".",".","2",".",".",".","6"],
  [".","6",".",".",".",".","2","8","."],
  [".",".",".","4","1","9",".",".","5"],
  [".",".",".",".","8",".",".","7","9"]
]
Output: true

Solution:

  • check 9*9 first

  • then check 3*3

  • if not adding temp and it is not '.', return false;

public boolean isValidSudoku(char[][] board){
    if(board == null || board.length == 0 || board[0] == null || board[0].length == 0) return false;
    int row = board.length, col = board[0].length;
    for(int i = 0; i < row; i++){
        for(int j = 0; j < col; j++){
            if(!isValid(board, i, i, 0,8)) return false;
            if(!isValid(board, 0,8,j,j)) return false;
        }
    }
    for(int i = 0; i < 3; i++){
        for(int j = 0; j < 3; j++){
            if(!isValid(board,i*3, i*3+2, j*3, j*3+2)) return false;
        }
    }
    return true;
}
private boolean isValid(char[][] board, int x1, int x2, int y1, int y2){
    Set<Character> set = new HashSet<>();
    for(int i = x1; i <= x2; i++){
        for(int j = y1; j <= y2; j++){
            char temp = board[i][j];
            if(temp != '.' && !set.add(temp)) return false;
        }
    }
    return true;
}

}

Last updated

Was this helpful?