36. 有效的数独
判断一个 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
形式的。
思路
本题两种思路,
-
思路一
通过设立三个hash map, 分别记录一个数字在某行,某列,以及某个九宫格中是否出现过
遍历数组,对于每次遍历,采用如下处理方式
若该值为空: continue
若该值为数字:
找出该位置对应的九宫格编号boxidx
分别判断该值在对应行,对应列,对应九宫格是否出现过
若有其中之一出现过:
则返回False 退出函数
若都没有出现过:
则继续执行
这样只需要一次遍历便可以得到最终结果。
代码如下:
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
rows = [{} for i in range(9)]
cols = [{} for i in range(9)]
boxs = [{} for i in range(9)]
for i in range(9):
for j in range(9):
num = board[i][j]
if num == ".": continue
boxidx = i // 3 * 3 + j // 3
rows[i][num] = rows[i].get(num, 0) + 1
cols[j][num] = cols[j].get(num, 0) + 1
boxs[boxidx][num] = boxs[boxidx].get(num, 0) + 1
if ((rows[i][num] > 1) or (cols[j][num] > 1) or (boxs[boxidx][num] > 1)):
return False
return True
-
思路二
通过三次遍历,分别获取行、列、九宫格的数据,然后判断是否有重复数值。
比较简单粗暴,没什么多提的,
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
def get_box(row, col):
box = []
start_row, start_col = row * 3, col * 3
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
box.append(board[i][j])
return box
def get_boxs():
boxs = []
for i in range(3):
for j in range(3):
boxs.append(get_box(i, j))
return boxs
def get_cols():
return [[row[i] for row in board] for i in range(9)]
def analyze(lines):
for line in lines:
unique_count = len(set(line)) - (1 if "." in line else 0)
real_count = 9 - line.count(".")
if unique_count != real_count:
return False
return True
rows = board
cols = get_cols()
boxs = get_boxs()
return analyze(rows) and analyze(cols) and analyze(boxs)