Simple java solution with 2d boolean arrays


  • 0
    X
    public class Solution {
        public boolean isValidSudoku(char[][] board) {
            boolean[][] rowCheck = new boolean[9][9];
            boolean[][] colCheck = new boolean[9][9];
            boolean[][] boxCheck = new boolean[9][9];
            
            for(int r=0;r<board.length;r++){
                for(int c=0;c<board[0].length;c++){
                    if(board[r][c] != '.'){
                        int num = board[r][c] - '0';
                        //check if number already exists for current row
                        //use num-1 to access index 0 to 8
                        if(rowCheck[r][num-1]){
                            return false;
                        }else{
                            rowCheck[r][num-1] = true;
                        }
                        //check if number already exists for current column
                        if(colCheck[c][num-1]){
                            return false;
                        }else{ 
                            colCheck[c][num-1] = true;
                        }
                        //check if number already exists for current square
                        //square are numbered 0 - 8 from top left to bottom right
                        if(boxCheck[3*(r/3)+c/3][num-1]){
                            return false;
                        }else{
                            boxCheck[3*(r/3)+c/3][num-1] = true;
                        }
                    }
                }
            }
            return true;
        }
    }
    

Log in to reply
 

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