LeetCode 36 有效的数独

// 将三种情况都考虑就好了,这里用flag数组进行判重



class Solution {
    public boolean isValidSudoku(char[][] board){
        boolean[] flag = new boolean[10];
        int n = board.length;
        int m = board[0].length;
        char c = 0;
        for (int i = 0 ;i < n; i ++){
            Arrays.fill(flag, false);
            for (int j = 0; j < m; j++){
                c = board[i][j];
                if (c >= '0' && c <= '9'){
                    if (flag[c - '0']) return false;
                    flag[c - '0'] = true;
                }
            }
        }

        for (int j = 0;j < m; j++){
            Arrays.fill(flag, false);
            for (int i = 0; i < n; i++){
                c = board[i][j];
                if (c >= '0' && c <= '9'){
                    if (flag[c - '0']) return false;
                    flag[c - '0'] = true;
                }
            }
        }

        for (int i = 0; i < 3; i ++){
            for (int j = 0; j < 3; j ++){
                Arrays.fill(flag, false);
                for (int row = i * 3; row < (i + 1) * 3; row ++) {
                    for (int col = j * 3; col < (j + 1) * 3; col ++){
                        c = board[row][col];
                        if (c >= '0' && c <= '9'){
                            if (flag[c - '0']) return false;
                            flag[c - '0'] = true;
                        }
                    }
                }
            }
        }
        
        return true;
    }
}

 

你可能感兴趣的:(LeetCode,Java)