Leetcode初学——有效的数独

题目:

归纳一下题目的要求:给出一个char型的二维数组九宫格,判断每一行,每一列,每一格内是否有重复的数字

代码如下:

class Solution {
    public boolean isValidSudoku(char[][] board) {
        Set<Character> set1=new HashSet<Character>();
        Set<Character> set2=new HashSet<Character>();
        Set<Character> set3=new HashSet<Character>();
        for(int i=0;i<board.length;i++){
            set1.clear();
            set2.clear();
            set3.clear();
            int count1 = 0;
            int count2 = 0;
            int count3 = 0 ;
            int row=i/3;
            int col=i%3;
            for(int j=0;j<board.length;j++){
                //对行进行判断
                if(board[i][j]!='.'){
                    count1++;
                    set1.add(board[i][j]);
                }
                //对列进行判断
                if(board[j][i]!='.'){
                    count2++;
                    set2.add(board[j][i]);
                }
                //对格进行判断
                if(board[row*3+j/3][col*3+j%3]!='.'){
                    count3++;
                    set3.add(board[row*3+j/3][col*3+j%3]);
                }
            }
            if(count1!=set1.size() || count2!=set2.size() || count3!=set3.size()) return  false;
        }
        return true;
    }
}

代码比较直接,为了增强可读性,写的也比较长

结果:

有疑问可以评论留言,我都会第一时间回复的

扫描二维码关注公众号,回复: 9088396 查看本文章
发布了57 篇原创文章 · 获赞 3 · 访问量 1078

猜你喜欢

转载自blog.csdn.net/qq_39377543/article/details/104117760