题目如下:
有效数独
解题思路:
分三步走:
- 首先判断各行是否有相同元素(除了“.”), 因为计算量最小,所以作为第一步。
- 判断各列是否有相同元素,计算量其次,所以作为第二步。
- 计算每个3*3 box 里是否存在相同元素,因为计算量最大,放到最后一步。
参考代码如下,beats 100%:
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
源码地址:
https://github.com/jediL/LeetCodeByPython
其它题目:[leetcode题目答案讲解汇总(Python版 持续更新)]
(https://www.jianshu.com/p/60b5241ca28e)
ps:如果您有好的建议,欢迎交流 :-D,
也欢迎访问我的个人博客 苔原带 (www.tundrazone.com)
网友评论