Valid Sudoku

给定一个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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值