【leetcode❤python】 36. Valid Sudoku

时间:2022-09-23 20:26:36

#-*- coding: UTF-8 -*-
#特定的九个格内1-9的个数至多为1
#依次检查每行,每列,每个子九宫格是否出现重复元素,如果出现返回false,否则返回true.
class Solution(object):
    def isValidSudoku(self, board):
        """
        :type board: List[List[str]]
        :rtype: bool
        """
       
        for i in range(len(board)):
            validate=[]
            for j in range(len(board[i])):
                if validate.__contains__(board[i][j]) and board[i][j]!='.':return False
                elif (board[i][j]<'1' or board[i][j]>'9') and board[i][j]!='.':return False
                else:validate.append(board[i][j])
        #列表转置
        boardT=map(list, zip(*board))
        
        for i in range(len(boardT)):
            validate=[]
            for j in range(len(boardT[i])):
                
                if validate.__contains__(boardT[i][j]) and boardT[i][j]!='.': return False
                elif (boardT[i][j]<'1' or boardT[i][j]>'9') and boardT[i][j]!='.':return False
                else:validate.append(boardT[i][j])
        
        i=0
        while i<=6:
            j=0
            while j<=6:
                validate=[]
                for n in range(3):
                    for m in range(3):
                         if validate.__contains__(board[i+n][j+m]) and board[i+n][j+m]!='.':return False
                         elif (board[i+n][j+m]<'1' or board[i+n][j+m]>'9') and board[i+n][j+m]!='.':return False
                         else:validate.append(board[i+n][j+m])
                j+=3
            i+=3
        
        return True