给定一个9*9的矩阵,判断该矩阵是否满足数独条件
入参矩阵python形式为:
[
["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/False。
要求理解:数独的条件就是每行/列,切分成9个3*3小块里数字唯一1-9。
则需要完成27次循环遍历9组字符列,如果出现数字重复,则返回False
否则返回True
上代码
class Solution(object):
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""
countdict = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0,
8: 0, 9: 0}
for row in board:
for e in row:
if e.isdigit():
countdict[int(e)] += 1
if countdict[int(e)] > 1:
return False
countdict = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0,
8: 0, 9: 0}
for i in range(9):
for j in range(9):
if board[j][i].isdigit():
countdict[int(board[j][i])] += 1
if countdict[int(board[j][i])] > 1:
return False
countdict = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0,
8: 0, 9: 0}
table = [(3, 3), (3, 6), (3, 9), (6, 3), (6, 6), (6, 9),
(9, 3), (9, 6), (9, 9)]
for each in table:
smallrow, smallcol = each[0], each[1]
for i in range(smallrow-3, smallrow):
for j in range(smallcol-3, smallcol):
if board[j][i].isdigit():
countdict[int(board[j][i])] += 1
if countdict[int(board[j][i])] > 1:
return False
countdict = {1: 0, 2: 0, 3: 0, 4: 0, 5: 0, 6: 0, 7: 0,
8: 0, 9: 0}
return True
LeetCode运行结果为Accepted
Runtime: 52 ms