Straight Forward Python Solution

  • 1

    Apart from defauttdict usage, this solution is pretty straight forward.

    Decompose each part of the Sudoku board that must fulfill the specified condition and return False as soon as one fails.

    from collections import defaultdict
    class Solution(object):
        def isValidSudoku(self, board):
            :type board: List[List[str]]
            :rtype: bool
            # Double-check basic assumptions
            if ( len(board) != 9 ):
                return False
            if ( len(board[0]) != 9 ):
                return False
            def validBoardPiece(numSet):
                dict = defaultdict(int)
                for numChar in numSet:
                    dict[numChar] += 1
                for number, amount in dict.items():
                    if (number != '.' and amount) > 1:
                        return False
                return True
            # Check Rows
            for row in board:
                if (not validBoardPiece(list(row))):
                    return False
            # Check Columns
            for columnIndex in range(9):
                column = []
                for rowIndex in range(9):
                if (not validBoardPiece(list(column))):
                    return False
            # Check Squares
            for boxY in range(3):
                for boxX in range(3):
                    box = []
                    for x in range(3):
                        for y in range(3):
                            box.append( board[(boxY*3) + y][(boxX*3) + x] )
                    if (not validBoardPiece(list(box))):
                        return False
            return True

Log in to reply

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