36. Valid Sudoku

Determine if a Sudoku is valid, according to: Sudoku Puzzles - The Rules.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'


A partially filled sudoku which is valid.

一刷
題解:
驗(yàn)證數(shù)獨(dú),分三次驗(yàn)證行,列以及9個(gè)3x3子塊就可以了。用set驗(yàn)證重復(fù)問題
Time Complexity - O(n2), Space Complexity - O(1)。

public class Solution {
    public boolean isValidSudoku(char[][] board) {
        if(board == null || board.length != 9 || board[0].length!=9) return false;
        Set<Integer> set = new HashSet<>();
        for(int i=0; i<9; i++){//row don't have duplicate
            set.clear();
            for(int j=0; j<9; j++){
                if(board[i][j] != '.' && !set.add(board[i][j] - '0'))//empty or contains duplicate one
                    return false;
            }
        }
        
        for(int j=0; j<9; j++){//col don't have duplicate
            set.clear();
            for(int i=0; i<9; i++){
                if(board[i][j] != '.' && !set.add(board[i][j] - '0'))//empty or contains duplicate one
                    return false;
            }
        }
        
        for(int i=1; i<9; i+=3){
            for(int j=1; j<9; j+=3){
                set.clear();
                for(int k=-1; k<=1; k++){
                    for(int l = -1; l<=1; l++){
                       if(board[i+k][j+l] != '.' && !set.add(board[i+k][j+l] - '0'))//empty or contains duplicate one
                        return false;  
                    }
                }
            }
        }
        
        return true;
    }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容