valid sudoku leetcode solution in java

Solutions on MaxInterview for valid sudoku leetcode solution in java by the best coders in the world

showing results for - "valid sudoku leetcode solution in java"
Irene
28 May 2020
1class Solution {
2    public boolean isValidSudoku(char[][] board) {
3        if(board == null || board.length == 0)
4            return false;
5        HashMap<Integer,Integer> [] rows = new HashMap[9];
6        HashMap<Integer,Integer> [] cols = new HashMap[9];
7        HashMap<Integer,Integer> [] boxes = new HashMap[9];
8        
9        for(int i = 0; i < 9 ; i++){
10            rows[i] = new HashMap<Integer,Integer>();
11            cols[i] = new HashMap<Integer,Integer>();
12            boxes[i] = new HashMap<Integer,Integer>();
13        }
14        int num =0;
15        for(int i =0 ; i < 9 ; i++){
16            for(int j=0; j < 9; j++){
17                char n = board[i][j];
18                if(board[i][j] != '.'){
19                 num = (int)n;
20                int box_index = (i/3)*3 + j/3;
21                rows[i].put(num,rows[i].getOrDefault(num,0)+1);
22                cols[j].put(num,cols[j].getOrDefault(num,0)+1);
23                boxes[box_index].put(num,boxes[box_index].getOrDefault(num,0)+1);
24                
25                if(rows[i].get(num) > 1 || cols[j].get(num) > 1 || boxes[box_index].get(num) > 1)
26                    return false;
27            }
28        }
29        }
30        
31        return true;
32    }
33}