LeetCode19-0713

有效的数独

判断一个 9x9 的数独是否有效。只需要根据以下规则,验证已经填入的数字是否有效即可。

数字 1-9 在每一行只能出现一次。
数字 1-9在每一列只能出现一次。
数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。

在这里插入图片描述
数独部分空格内已填入了数字,空白格用 ‘.’ 表示。

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        #起初我使用的是[dict()]*9,发现list中引用的是同一个对象,更改其中一个其他也会改变
        row_hash=[dict() for i in range(9)]
        col_hash=[dict() for i in range(9)]
        box_hash=[dict() for i in range(9)]
        for r_ind,row in enumerate(board):
            for c_ind,num in enumerate(row):
                if num == '.':
                    continue
                if num not in row_hash[r_ind]:
                    row_hash[r_ind][num]=1
                else:
                    return False
                if num not in col_hash[c_ind]:
                    col_hash[c_ind][num]=1
                else:
                    return False
                
                box_ind=(r_ind//3)*3+c_ind//3
                
                if num not in box_hash[box_ind]:
                    box_hash[box_ind][num]=1
                else:
                    return False
        return True
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值