因为每次按行遍历,因此建立一个行哈希表,9个列哈希表,和3个方格哈希表,通过查询元素是否在相应表中来判断:
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
columnsValid = [{}, {}, {}, {}, {}, {}, {}, {}, {}]
for i, r in enumerate(board):
rowsValid = {}
if i % 3 == 0:
gridsValid = [{}, {}, {}]
for j, c in enumerate(r):
if c != '.':
if c in rowsValid:
return False
else:
rowsValid[c] = True
if c in columnsValid[j]:
return False
else:
columnsValid[j][c] = True
if c in gridsValid[j // 3]:
return False
else:
gridsValid[j // 3][c] = True
return True