5-line Python solution, set, scan 4 times


  • 0
    K
    def isValidSudoku(self, board):
        dotNum = sum(row.count('.') for row in board)
        # check rows
        if sum(len({char for char in row if char != '.'}) for row in board) + dotNum < 81: return False
        # check columns
        if sum(len({board[j][i] for j in xrange(9) if board[j][i] != '.'}) for i in xrange(9)) + dotNum < 81: return False
        # check 3x3 squares
        if sum(len({board[i + m][j + n] for m in (0, 1, 2) for n in (0, 1, 2) if board[i + m][j + n] != '.'}) for i in (0, 3, 6) for j in (0, 3, 6)) + dotNum < 81: return False
        return True

  • 0
    B

    I don't understand; It seems like each check just checks that the board has the correct number of squares. Each one appears to check that the number of non '.' squares + the number of '.' squares is always the total number of squares on the board, which would always be the case.


  • 0
    K

    {char for char in row if char != '.'} is set comprehension and I will get a set, duplicates are removed.


  • 0
    B

    Got it. Thanks!


Log in to reply
 

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