36.有效的数独
判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。
数字 1-9 在每一行只能出现一次。
数字 1-9 在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。
上图是一个部分填充的有效的数独。
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。
说明:
一个有效的数独(部分已被填充)不一定是可解的。 只需要根据以上规则,验证已经填入的数字是否有效即可。 给定数独序列只包含数字 1-9 和字符 ‘.’ 。 给定数独永远是 9x9 形式的。
一个简单的解决方案是遍历该 9 x 9 数独 三 次,以确保:
行中没有重复的数字。
列中没有重复的数字。
3 x 3 子数独内没有重复的数字。
1. 先创建字典:
rows = [{} for i in range(9)]
columns = [{} for i in range(9)]
boxes = [{} for i in range(9)]
2. 依次获得每行,每列,每个3x3小格的键值(数值:数目)
for i in range(9):
for j in range(9):
num = board[i][j]
if num != '.':
num = int(num)
# 这个设计很巧妙获得了每个[i][j]对应的3x3九宫小格
box_index = (i // 3) * 3 + j // 3
# keep the current cell value
rows[i][num] = rows[i].get(num, 0) + 1
columns[j][num] = columns[j].get(num, 0) + 1
boxes[box_index][num] = boxes[box_index].get(num, 0) + 1
比如输入:
isValidSudoku([
["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"])
输出:
rows:
[{5: 1, 3: 1, 7: 1},
{6: 1, 1: 1, 9: 1, 5: 1},
{9: 1, 8: 1, 6: 1},
{8: 1, 6: 1, 3: 1},
{4: 1, 8: 1, 3: 1, 1: 1},
{7: 1, 2: 1, 6: 1},
{6: 1, 2: 1, 8: 1},
{4: 1, 1: 1, 9: 1, 5: 1},
{8: 1, 7: 1, 9: 1}]
columns:
[{5: 1, 6: 1, 8: 1, 4: 1, 7: 1},
{3: 1, 9: 1, 6: 1}, {8: 1},
{1: 1, 8: 1, 4: 1},
{7: 1, 9: 1, 6: 1, 2: 1, 1: 1, 8: 1},
{5: 1, 3: 1, 9: 1},
{2: 1},
{6: 1, 8: 1, 7: 1},
{3: 1, 1: 1, 6: 1, 5: 1, 9: 1}]
boxes:
[{5: 1, 3: 1, 6: 1, 9: 1, 8: 1},
{7: 1, 1: 1, 9: 1, 5: 1},
{6: 1},
{8: 1, 4: 1, 7: 1},
{6: 1, 8: 1, 3: 1, 2: 1},
{3: 1, 1: 1, 6: 1},
{6: 1},
{4: 1, 1: 1, 9: 1, 8: 1},
{2: 1, 8: 1, 5: 1, 7: 1, 9: 1}]
3. 判断字典中是否有数目大于1的键,是则数独有误
if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:
return False
4. 下面是完整代码
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
# init data
# 创建[{}, {}, {}, {}, {}, {}, {}, {}, {}]
rows = [{} for i in range(9)]
columns = [{} for i in range(9)]
boxes = [{} for i in range(9)]
# validate a board
for i in range(9):
for j in range(9):
num = board[i][j]
if num != '.':
num = int(num)
box_index = (i // 3) * 3 + j // 3
# keep the current cell value
rows[i][num] = rows[i].get(num, 0) + 1
columns[j][num] = columns[j].get(num, 0) + 1
boxes[box_index][num] = boxes[box_index].get(num, 0) + 1
# check if this value has been already seen before
if rows[i][num] > 1 or columns[j][num] > 1 or boxes[box_index][num] > 1:
return False
return True