Share My Python Solution


  • 0
    M

    In this case, the difficult point is to compute the grid index of a certain element, given column index and row index. And the answer is: gridCount = int(3*math.floor(rowCount/3) + math.floor(colCount/3))

    class Solution:
        # @param board, a 9x9 2D array
        # @return a boolean
        def isValidSudoku(self, board):
            rowSets = []
            colSets = []
            gridSets = []
            
            rowCount = 0
            colCount = 0
            gridCount = 0
            
            
            for row in board:
                rowSets.append([])
                for ele in row:
    
                    import math
    
                    gridCount = int(3*math.floor(rowCount/3) + math.floor(colCount/3))
                    
                    if ele not in [".", "1", "2", "3", "4", "5", "6", "7", "8", "9"]:
                        return False
                    
                    if rowCount == 0:
                        colSets.append([])
                        
                    if rowCount%3 == 0 and colCount%3 == 0:
                        gridSets.append([])
    
                    if ele != ".":
                        gridSets[gridCount].append(ele)
                        rowSets[rowCount].append(ele)
                        colSets[colCount].append(ele)
                    
                    colCount += 1
    
                                  
                colCount = 0
                rowCount += 1
            
    
            for i in range(9):
                if((not self.checkDuplicate(rowSets[i])) or (not self.checkDuplicate(colSets[i])) or (not self.checkDuplicate(gridSets[i]))):
                    return False
            
            return True
        
        def checkDuplicate(self, l):
            actualCount = len(l)
    
            targetSet = set(l)
            setCount = len(targetSet)
    
            if setCount < actualCount:
                return False
            return True

Log in to reply
 

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