4ms Java solution with bit operation


  • 0
    A
    public class Solution {
        public boolean isValidSudoku(char[][] board) {
            for(int row=0; row < 9; row++) {
                int flag1 = 0;
                int flag2 = 0;
                int flag3 = 0;
                
                for(int col=0; col < 9; col++) {
                    if(board[row][col] != '.') {
                        int num = board[row][col] - '0';
                        if((flag1 >>> num & 1) == 1)
                            return false;
                            
                        flag1 |= 1 << num;
                    }
                    
                    if(board[col][row] != '.') {
                        int num = board[col][row] - '0';
                        if((flag2 >>> num & 1) == 1)
                            return false;
                            
                        flag2 |= 1 << num;
                    }
                    
                    int rowT = col / 3 + row / 3 * 3;
                    int colT = col % 3 + row * 3 % 9;
                    
                    if(board[rowT][colT] != '.') {
                        int num = board[rowT][colT] - '0';
                        if((flag3 >>> num & 1) == 1)
                            return false;
                            
                        flag3 |= 1 << num;
                    }
                }
            }
            
            return true;
        }
    }

Log in to reply
 

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