Leetcode 36.有效的数独
1 题目描述(Leetcode题目链接)
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
- 数字 1-9 在每一行只能出现一次。
- 数字 1-9 在每一列只能出现一次。
- 数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
输入:
[
["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 题解
如果暴力求解的话,需要在每个元素上判断行、列、块中是否有重复元素,这样的话非常慢,所有我们可以将行、列、块都用哈希表存储,key值为第几个行、列、块,所以3个哈希表的key的范围为0~8。现在在于当我们遍历数组的时候怎么判读元素是哪个行、列、块的。行和列很容易判断,分别对应行标和列表,至于它是哪个块,则需要简单变换一下,块号为: i / / 3 ∗ 3 + j / / 3 i//3*3 + j//3 i//3∗3+j//3。
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
line = dict.fromkeys(range(9), "") #行
column = dict.fromkeys(range(9), "") #列
block = dict.fromkeys(range(9), "") #块
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
if board[i][j] in line[i] or board[i][j] in column[j] or board[i][j] in block[i//3*3 + j//3]:
return False
else:
line[i] += board[i][j]
column[j] += board[i][j]
block[i//3*3 + j//3] += board[i][j]
return True