标签:row 哈希表 输出 lse 数字 图片 png 空格 解决
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
1-9
在每一行只能出现一次。1-9
在每一列只能出现一次。1-9
在每一个以粗实线分隔的 3x3
宫内只能出现一次。上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 ‘.‘
表示。
示例 1:
输入: [ ["5","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] 输出: true
示例 2:
输入: [ ["8","3",".",".","7",".",".",".","."], ["6",".",".","1","9","5",".",".","."], [".","9","8",".",".",".",".","6","."], ["8",".",".",".","6",".",".",".","3"], ["4",".",".","8",".","3",".",".","1"], ["7",".",".",".","2",".",".",".","6"], [".","6",".",".",".",".","2","8","."], [".",".",".","4","1","9",".",".","5"], [".",".",".",".","8",".",".","7","9"] ] 输出: false 解释: 除了第一行的第一个数字从 5 改为 8 以外,空格内其他数字均与 示例1 相同。 但由于位于左上角的 3x3 宫内有两个 8 存在, 因此这个数独是无效的。
说明:
1-9
和字符 ‘.‘
。9x9
形式的。既然要针对三个模块查重,那么就分别建立三个模块(行、列、box)。每个模块都应该有9个哈希表和集合。按照行列一次循环就可以解决问题。
1 class Solution: 2 def isValidSudoku(self, board: List[List[str]]) -> bool: 3 row = [{} for i in range(9)] # 行集合 9行 4 column = [{} for i in range(9)] # 列集合 9列 5 box = [{} for i in range(9)] # 宫格集合 3*3=9个宫格 6 7 for i in range(9): 8 for j in range(9): 9 if board[i][j]!=‘.‘: # 是数字则循环 10 num = int(board[i][j]) 11 row[i][num] = row[i].get(num,0) + 1 # 在当前行里添加 12 column[j][num] =column[j].get(num,0) + 1 # 在当前列里添加 13 box[int(i//3)*3+int(j//3)][num] = box[int(i//3)*3+int(j//3)].get(num,0)+ 1 # 在当前宫格内添加 14 15 if row[i][num]>1 or column[j][num]>1 or box[int(i//3)*3+int(j//3)][num]>1: # 若再次出现则返回false 16 return False 17 return True
标签:row 哈希表 输出 lse 数字 图片 png 空格 解决
原文地址:https://www.cnblogs.com/king-lps/p/10740306.html