Leetcode 36

Question

Solution

可以通过set来比较是否有重复元素,注意剔除”.”。

先创建一个检测unit的函数,然后判断行,列,3*3的时候调用unit函数。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
return (self.roww(board) and self.coll(board) and self.square(board))

def unitt(self, unit):
unit = [elem for elem in unit if elem !="."]
return len(set(unit)) == len(unit)

def roww(self, board):
for row in board:
if not self.unitt(row):
return False
return True

def coll(self, board):
for col in zip(*board):
if not self.unitt(col):
return False
return True

def square(self, board):
for i in (0, 3, 6):
for j in (0, 3, 6):
square = [board[x][y] for x in range(i, i+3) for y in range(j, j+3)]
if not self.unitt(square):
return False
return True