HashMap of HashMap - Short and Easy Java solution


  • 0
    R

    Returning false if any of the 3 rules are violated:

    public boolean isValidSudoku(char[][] board) {

        HashMap<Integer,HashMap<Integer,Integer>> hm = new HashMap<>();
        
        // populate HashMap
        for(int i = 0;i<board.length;i++){
            
            for(int j =0;j<board[0].length;j++) {
                
                if(board[i][j] != '.') {
                    int num = Character.getNumericValue(board[i][j]);
                    if(hm.containsKey(num)) { // Existing key ; check the entries
                        HashMap<Integer,Integer> childHM = hm.get(num);
                        
                        for(Map.Entry<Integer,Integer> e: childHM.entrySet()) {
                            
                            if((Integer)e.getKey() == i || (Integer)e.getValue() == j)
                                return false;
                            
                            int prevKey = (Integer)e.getKey();
                            int prevVal = (Integer)e.getValue();
                            if((prevKey/3 == i/3) && (prevVal/3 == j/3) && Math.abs(prevKey-i) <= 2  &&  Math.abs(prevVal-j) <= 2){
                                
                                return false;
                            }
                        }
                        
                        childHM.put(i,j);
                    }
                
                    else {
                        HashMap<Integer,Integer> childHM = new HashMap<Integer,Integer>();
                        childHM.put(i,j);
                        hm.put(num,childHM);
                    }
                } 
            }
        }
        
       
        
        return true;
        
    }

Log in to reply
 

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