Table of Content
题目如下:
解题思路:
分三步走:
1. 首先判断各行是否有相同元素(除了“.”), 因为计算量最小,所以作为第一步。
2. 判断各列是否有相同元素,计算量其次,所以作为第二步。
3. 计算每个3*3 box 里是否存在相同元素,因为计算量最大,放到最后一步。
参考代码如下,beats 100%:
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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
class Solution: def isValidSudoku(self, board): """ :type board: List[List[str]] :rtype: bool """ # check every row valid or not for row in board: temp_row = [] for num in row: if num == ".": continue elif num not in temp_row: temp_row.append(num) else: return False # check every col valid or not i = 0 while i < 9: temp_col = [] for row in board: if row[i] == ".": continue elif row[i] not in temp_col: temp_col.append(row[i]) else: return False i += 1 # check every 3*3 valid or not: s = 0 while s <= 6: col = 0 while col <= 6: temp_box = [] for row in board[s:s + 3]: for num in row[col:col + 3]: if num == ".": continue elif num not in temp_box: temp_box.append(num) else: return False col += 3 s += 3 return True |
如果您有好的建议,欢迎来信与我交流

也欢迎关注微信公众号“苔原带”

