My 5ms Java solution which beats almost 100% solutions


  • 1
    T

    public class Solution {
    public boolean isValidSudoku(char[][] board) {
    if (board==null)
    return false;
    //check rows
    if(checkRows(board))
    {
    //return true;
    //check columns
    if(checkColumns(board))
    //checkBoxes
    return checkBoxes(board);
    }
    return false;

    }
    public boolean checkRows(char[][] board)
    {
        
        for(int i=0;i<9;i++)
        {
            boolean[] val=new boolean[10];
            for(int j=0;j<9;j++)
            {
                if(board[i][j]!='.')
                {
                     int k=Character.getNumericValue(board[i][j]);
                    if(k==-1||val[k])
                        return false;
                    else
                    {
                        val[k]=true;
                    }
                }
            }
        }
        return true;
    }
     public boolean checkColumns(char[][] board)
    {
        
        for(int i=0;i<9;i++)
        {
            boolean[] val=new boolean[10];
            for(int j=0;j<9;j++)
            {
                if(board[j][i]!='.')
                {
                    int k=Character.getNumericValue(board[j][i]);
                    if(k==-1||val[k])
                        return false;
                    else
                    {
                        val[k]=true;
                    }
                }
            }
        }
        return true;
    }
    public boolean checkBoxes(char[][] board)
    {
       return  checkBoxes(board,0,3,0,3)&&
        checkBoxes(board,0,3,3,6)&&
        checkBoxes(board,0,3,6,9)&&
        checkBoxes(board,3,6,0,3)&&
        checkBoxes(board,3,6,3,6)&&
        checkBoxes(board,3,6,6,9)&&
        checkBoxes(board,6,9,0,3)&&
        checkBoxes(board,6,9,3,6)&&
        checkBoxes(board,6,9,6,9);
    }
    public boolean checkBoxes(char[][] board, int rs, int rl,int cs,int cl)
    {
        boolean[] val=new boolean[10];
        for(int i=rs;i<rl;i++)
        {
            for(int j=cs;j<cl;j++)
            {
                if(board[j][i]!='.')
                {
                    int k=Character.getNumericValue(board[j][i]);
                    if(k==-1||val[k])
                        return false;
                    else
                    {
                        val[k]=true;
                    }
                }
            }
        }
        return true;
    }
    

    }


Log in to reply
 

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