Java solution- easy to understand


  • 1
    R
    public class Solution {
    public boolean isValidSudoku(char[][] board) {
        int[][] row = new int[9][9];
        int[][] col = new int[9][9];
        int[][][] bb = new int[3][3][9];
        
        for(int i = 0; i<9; i++){//row
            for(int j = 0; j<9; j++){//col
                if(board[i][j]=='.'){
                    continue;
                }
                else{
                    int index = board[i][j] - '0' - 1;
                    row[i][index]+=1;
                    if(row[i][index]>1) return false;
                    col[j][index]+=1;
                    if(col[j][index]>1) return false;
                    bb[i/3][j/3][index]+=1;
                    if(bb[i/3][j/3][index]>1) return false;
                }
            }
        }
        return true;
    }
    

    }


  • 0
    H

    public class Solution {
    public boolean isValidSudoku(char[][] board) {
    HashSet<Character> set = new HashSet<Character>();

        // check rows
        for (int i = 0; i < board.length; i++) {
            set.clear();
            for (int j = 0; j < board.length; j++) {
                if (board[i][j] != '.' && !set.add(board[i][j]))
                    return false;
            }
        }
    
        // check columns
        for (int j = 0; j < board.length; j++) {
            set.clear();
            for (int i = 0; i < board.length; i++) {
                if (board[i][j] != '.' && !set.add(board[i][j]))
                    return false;
            }
        }
    
        // check each sub box, there're p*q sub-boxes
        int totalBoxes = board.length / 3;
        for (int p = 0; p < totalBoxes; p++) {
            for (int q = 0; q < totalBoxes; q++) {
                set.clear();
                for (int i = p * 3; i < p * 3 + 3; i++) {
                    for (int j = q * 3; j < q * 3 + 3; j++) {
                        if (board[i][j] != '.' && !set.add(board[i][j]))
                            return false;
                    }
                }
            }
        }
    
        return true;
    }
    

    }


Log in to reply
 

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