Simple python code that follow intuition


  • 0
    B
    class Solution:
    # @param board, a 9x9 2D array
    # @return a boolean
    def isValidSudoku(self, board):
        def isValidArray(A):
            B=filter(lambda x:x!='.',A)
            S=set(B)
            return len(S)==len(B)
        def getline(A,num,row=True):
            if row:
                res=[A[num][i] for i in range(len(A[1]))]
            else:
                res=[A[i][num] for i in range(len(A))]
            return res
        def getsubboard(A,num):
            row=num/3*3
            col=num%3*3
            res=[A[i][j] for i in range(row,row+3) for j in range(col,col+3)]
            return res
        for i in range(len(board)):
            row=getline(board,i)
            col=getline(board,i,row=False)
            subboard=getsubboard(board,i)
            if not isValidArray(row) or  not isValidArray(col) or not isValidArray(subboard):
                return False
        return True

  • 0
    B
    class Solution:
        # @param board, a 9x9 2D array
        # @return a boolean
        def isValidSudoku(self, board):
            for i in range(len(board)):
                if not self.isValid(board[i]):
                    return False
            L = self.reverse(board)
            for i in range(len(L)):
                if not self.isValid(L[i]):
                    return False
            for i in range(0, 3):
                for j in range(0, 3):
                    P = self.getSub(board, i, j)
                    if not self.isValid(P):
                        return False
            return True
            
        def isValid(self, line):
            for temp in line:
                if temp != '.':
                    if line.count(temp) > 1:
                        return False
            return True
        
        def reverse(self, board):
            L = [''] * 9
            for i in range(0, 9):
                for j in range(0, 9):
                    L[i] += board[j][i]
            return L
            
        def getSub(self, board, x, y):
            x = 3 * x
            y = 3 * y
            L = ''
            for i in range(x, x + 3):
                for j in range(y, y + 3):
                    L += board[i][j]
            return L

  • 0
    T
    This post is deleted!

  • 0
    H

    You can actually combine getline and getsubboard into one function


Log in to reply
 

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