5ms easy understanding java solution


  • 0
    V
    public class Solution {
        public boolean isValidSudoku(char[][] board) {
            return isValidColunms(board) && isValidRows(board) && isValidBlock(board);
        }
        private boolean isValidColunms(char [][] board){
            int [] flags = new int[10];
            for(int i = 0;i < 10;i++)
                flags[i] = -1;
            for(int i = 0;i < 9;i++)
                for(int j = 0;j < 9;j++){
                    if(!isValidNumber(flags,board[i][j],i))
                        return false;
                }
            return true;
        }
        private boolean isValidRows(char [][] board){
            int [] flags = new int[10];
            for(int i = 0;i < 10;i++)
                flags[i] = -1;
            for(int j = 0;j < 9;j++)
                for(int i = 0;i < 9;i++){
                    if(!isValidNumber(flags,board[i][j],j))
                        return false;
                }
            return true;
        }
        private boolean isValidBlock(char [][] board)
        {
            int [] flags = new int[10];
            for(int i = 0;i < 10;i++)
                flags[i] = -1;
            for(int k = 0;k < 9;k++)
            {  // form top to bottom , left to right
                for(int i = 0;i < 3;i++)
                    for(int j = 0;j < 3;j++)
                    {
                        //  k/3*3 and k%3*3 is a offset 
                         if(!isValidNumber(flags,board[i+k/3*3][j+k%3*3],k))
                            return false;
                    }
            }
            return true;
        }
        private boolean isValidNumber(int [] flags,char ch,int flag)
        {
            if(ch == '.')
                return true;
             else if(ch <= '9' && ch >= '0'){
                int pos = ch - '0';
                if(flags[pos] == flag)
                     return false;
                flags[pos]  = flag;
              }
             else 
                 return false;
            return true;
        }
        
    }
    

  • 0
    M

    Hello,

    Why does your solution take only 5ms for you but 32ms for me?


  • 0
    A

    @Molen Same for me 31ms


Log in to reply
 

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