Share my AC python solution.


  • 0
    L

    create some tiny function, and the code looks better.

    class Solution:
    # @param board, a 9x9 2D array
    # @return a boolean
    def isValidSudoku(self, board):
        def isArrValid(arr): # core function.
            hash={};
            valid=True;
            for num in arr:
                if(num=='.'):
                    continue;
                if(num not in hash):
                    hash[num]=0;
                else:
                    valid=False;
                    break;
            return valid;
    
        def isRowValid(row,board):            
            res=[]
            for i in range(9):
                res.append(board[row][i]);
            return isArrValid(res);
    
        def isColValid(col,board):
            res=[]
            for i in range(9):
                res.append(board[i][col]);
            return isArrValid(res);
    
        def isBlockValid(row,col,board):
            res=[];
            for r in range(row*3,(row+1)*3):
                for c in range(col*3,(col+1)*3):
                    res.append(board[r][c]);
            return isArrValid(res);
    
        for r in range(9):
            if(isRowValid(r,board)==False):
                return False;
            if(isColValid(r,board)==False):
                return False;
        for r in range(3):
            for c in range(3):
                if(isBlockValid(r,c,board)==False):
                    return False;
        return True;

Log in to reply
 

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