有效的数独
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9
在每一行只能出现一次。
数字 1-9
在每一列只能出现一次。
数字 1-9
在每一个以粗实线分隔的 3x3
宫内只能出现一次。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
#起初我使用的是[dict()]*9,发现list中引用的是同一个对象,更改其中一个其他也会改变
row_hash=[dict() for i in range(9)]
col_hash=[dict() for i in range(9)]
box_hash=[dict() for i in range(9)]
for r_ind,row in enumerate(board):
for c_ind,num in enumerate(row):
if num == '.':
continue
if num not in row_hash[r_ind]:
row_hash[r_ind][num]=1
else:
return False
if num not in col_hash[c_ind]:
col_hash[c_ind][num]=1
else:
return False
box_ind=(r_ind//3)*3+c_ind//3
if num not in box_hash[box_ind]:
box_hash[box_ind][num]=1
else:
return False
return True