1 """ 2 Determine if a 9x9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules: 3 Each row must contain the digits 1-9 without repetition. 4 Each column must contain the digits 1-9 without repetition. 5 Each of the 9 3x3 sub-boxes of the grid must contain the digits 1-9 without repetition. 6 A partially filled sudoku which is valid. 7 The Sudoku board could be partially filled, where empty cells are filled with the character '.'. 8 Example 1: 9 Input: 10 [ 11 ["5","3",".",".","7",".",".",".","."], 12 ["6",".",".","1","9","5",".",".","."], 13 [".","9","8",".",".",".",".","6","."], 14 ["8",".",".",".","6",".",".",".","3"], 15 ["4",".",".","8",".","3",".",".","1"], 16 ["7",".",".",".","2",".",".",".","6"], 17 [".","6",".",".",".",".","2","8","."], 18 [".",".",".","4","1","9",".",".","5"], 19 [".",".",".",".","8",".",".","7","9"] 20 ] 21 Output: true 22 Example 2: 23 Input: 24 [ 25 ["8","3",".",".","7",".",".",".","."], 26 ["6",".",".","1","9","5",".",".","."], 27 [".","9","8",".",".",".",".","6","."], 28 ["8",".",".",".","6",".",".",".","3"], 29 ["4",".",".","8",".","3",".",".","1"], 30 ["7",".",".",".","2",".",".",".","6"], 31 [".","6",".",".",".",".","2","8","."], 32 [".",".",".","4","1","9",".",".","5"], 33 [".",".",".",".","8",".",".","7","9"] 34 ] 35 Output: false 36 Explanation: Same as Example 1, except with the 5 in the top left corner being 37 modified to 8. Since there are two 8's in the top left 3x3 sub-box, it is invalid. 38 """ 39 """ 40 很考验python功底的一道题 41 """ 42 class Solution: 43 def isValidSudoku(self, board): 44 for num1 in board: 45 if not self.isRep(num1): 46 return False 47 for col in zip(*board): # !!!矩阵的转置 48 if not self.isRep(col): 49 return False 50 for i in (0, 3, 6): 51 for j in (0, 3, 6): 52 square = [board[x][y] for x in range(i, i + 3) for y in range(j, j + 3)] 53 if not self.isRep(square): 54 return False 55 return True 56 57 def isRep(self, unit): 58 unit = [i for i in unit if i != '.'] 59 return len(set(unit)) == len(unit) # !!!判断数组中有无重复值得方法。set