Concise java code using bitMap to validate


  • 0
    B

    The idea is very simple, keep three different bit map for rows cols and 9 small matrix.

    public class Solution {
        public boolean isValidSudoku(char[][] board) {
            int[] rowMap = new int[9];
            int[] colMap = new int[9];
            int[] matrixMap = new int[9];
            for (int i = 0 ; i < 9 ; i++){
                for (int j = 0 ; j < 9 ; j++){
                    if (board[i][j] != '.'){
                        int num = board[i][j] - '0';
                        if (check(num, rowMap, i) && check(num, colMap, j) && check(num, matrixMap, (i / 3) * 3 + j / 3)){
                            continue;
                        }else{
                            return false;
                        }
                    }
                }
            }
            return true;
        }
        private boolean check (int num, int[] Map, int index){
            int Mask = Map[index];
            if (((Mask >> num) & 1) == 1){
                return false;
            }
            Map[index] |= 1 << num;
            return true;
        }
    }
    

Log in to reply
 

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