其他分享
首页 > 其他分享> > 36.有效的数独

36.有效的数独

作者:互联网

 

 

输入:board =
[["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"]]
输出:true

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

class Solution {
    boolean judge1 (char[][] board,int x){
        int a[]={0,1,1,1,1,1,1,1,1,1};
        for(int i=0;i<9;++i){
            //判断是数字
            if(board[x][i]>='0'&&board[x][i]<='9'){
                int cnt =(int)board[x][i] - (int)'0';
                if(a[cnt]==1){
                    a[cnt]=0;
                }
                else {
                    return false;
                }
                //int cnt =board[x][i] - '0';
            }
        }
        return true;
    }
    boolean judge2 (char[][] board,int y){
        int a[]={0,1,1,1,1,1,1,1,1,1};
        for(int i=0;i<9;++i){
            //判断是数字
            if(board[i][y]>='0'&&board[i][y]<='9'){
                int cnt =(int)board[i][y] - (int)'0';
                if(a[cnt]==1){
                    a[cnt]=0;
                }
                else {
                    return false;
                }
                
            }
        }
        return true;
    }
    boolean judge3 (char[][] board,int x,int y){
        int a[]={0,1,1,1,1,1,1,1,1,1};
        for(int i=x;i<x+3;++i){
            for(int j=y;j<y+3;++j){
                if(board[i][j]>='0'&&board[i][j]<='9'){
                    int cnt = (int)board[i][j] - (int)'0';
                    if(a[cnt]==1){
                    a[cnt]=0;
                }
                else {
                    return false;
                }
                }
            }
        }
        return true;
    }
    public boolean isValidSudoku(char[][] board) {
        for(int i=0;i<9;++i){
            if(judge1(board,i)==false){
                return false;
            }
            if(judge2(board,i)==false){
                return false;
            }
        }
        for(int i=0;i<9;i+=3){
            for(int j=0;j<9;j+=3){
                if(judge3(board,i,j)==false){
                    return false;
                }
            }
        }
        return true;
    }
}

 

标签:cn,int,36,char,有效,board,&&,转载,数独
来源: https://www.cnblogs.com/h404nofound/p/16590368.html