My 7ms solution


  • 0
    P
    public boolean isValidSudoku(char[][] board) {
        if(board == null || board.length == 0){
            return false;
        }   
        
        // check every sub-boxes
        for(int m=0; m<9; m+=3){
            for(int n=0; n<9; n+=3){
                Set<Character> set = new HashSet<>();
                for(int i=m; i<m+3; i++){
                    for(int j=n;j<n+3;j++){
                        if(board[i][j] !='.'){
                            if(!set.add(board[i][j])){
                                return false;
                            }
                        }
                    }
                }
            }
        }
        
        
        for(int i = 0; i < board.length; i++){
            Set<Character> setRow = new HashSet<>();
            Set<Character> setCol = new HashSet<>();
            for(int j=0; j < board[0].length; j++){
                if(board[i][j] != '.') {       // check every row
                    if( !setRow.add(board[i][j]) ){
                        return false;
                    }
                }
                
                if(board[j][i] != '.') {  // check every col
                    if( !setCol.add(board[j][i]) ){
                        return false;
                    }
                }
            }
        }
        
        return true;
        
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.