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.

一刷
题解:
验证数独,分三次验证行,列以及9个3x3子块就可以了。用set验证重复问题
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;
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容