Java bit operation solution


  • 0
    T

    Using 3 arrays to represent the rows, columns and squares. Each includes 9 elements, each element is a 9 bits integer, 1 on position x means x is in the corresponding row/column/square.
    ''''

    public boolean isValidSudoku(char[][] board) {
        int[] row = {0, 0, 0, 0, 0, 0, 0, 0, 0};
        int[] col = {0, 0, 0, 0, 0, 0, 0, 0, 0};
        int[] squ = {0, 0, 0, 0, 0, 0, 0, 0, 0};
        
        for (int i = 0; i < 9; i++)
            for (int j = 0; j < 9; j++) {
                if (board[i][j] == '.') continue;
                int val = board[i][j] - '0';
                if (((row[i] >> (val - 1)) & 1) == 1) return false;
                row[i] += 1 << (val - 1);
                if (((col[j] >> (val - 1)) & 1) == 1) return false;
                col[j] += 1 << (val - 1);
                int sq_pos = i - i % 3 + j / 3;
                if (((squ[sq_pos] >> (val - 1)) & 1) == 1) return false;
                squ[sq_pos] += 1 << (val - 1);
            }
        return true;
    }
    

    ''''


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.