【LeetCode】36. 有效的数独

1 问题

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

数字 1-9 在每一行只能出现一次。

数字 1-9 在每一列只能出现一次。

数字 1-9 在每一个以粗实线分隔的 3x3 宫内只能出现一次。(请参考示例图)

注意:

一个有效的数独(部分已被填充)不一定是可解的。

只需要根据以上规则,验证已经填入的数字是否有效即可。

空白格用 '.' 表示。

示例 1:

输入:board =

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

示例 2:

输入:board =

python 复制代码
[["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 存在, 因此这个数独是无效的。

2 答案

这题直接不会

官方解,利用哈希表,哈希表也可以是列表,矩阵的表示方法也很妙,非常值得学习

python 复制代码
class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:

        row = [[0] * 9 for _ in range(9)]
        col = [[0] * 9 for _ in range(9)]
        block = [[0] * 9 for _ in range(9)]

        for i in range(9):
            for j in range(9):
                if board[i][j] != '.':
                    num = int(board[i][j]) - 1
                    b = (i // 3) * 3 + j // 3   # 3*3 小矩阵的第b个矩阵,这个很妙
                    if row[i][num] or col[j][num] or block[b][num]:  # 看这几个位置是否有值,如果有一个有,则返回 False
                        return False
                    row[i][num] = col[j][num] = block[b][num] = 1
        return True

3 知识点

哈希表(Hash Table):也叫做散列表。是根据关键码值(Key Value)直接进行访问的数据结构。

哈希表通过「键 key 」和「映射函数 Hash(key) 」计算出对应的「值value」,把关键码值映射到表中一个位置来访问记录,以加快查找的速度。这个映射函数叫做「哈希函数(散列函数)」,存放记录的数组叫做「哈希表(散列表)」。

https://blog.csdn.net/zy_dreamer/article/details/131036258

相关推荐
神里流~霜灭2 分钟前
蓝桥备赛指南(12)· 省赛(构造or枚举)
c语言·数据结构·c++·算法·枚举·蓝桥·构造
小杨爱学习zb9 分钟前
学习总结 网格划分+瞬态求解设置
笔记·学习·算法
双叶83622 分钟前
(C语言)单链表(1.0)(单链表教程)(数据结构,指针)
c语言·开发语言·数据结构·算法·游戏
uhakadotcom1 小时前
OpenAI 的 PaperBench:AI 研究复现基准测试工具
算法·面试·github
凯强同学1 小时前
第十四届蓝桥杯大赛软件赛省赛Python 大学 C 组:6.棋盘
python·算法·蓝桥杯
wuqingshun3141591 小时前
蓝桥杯 切割
数据结构·c++·算法·职场和发展·蓝桥杯
艾妮艾妮1 小时前
C语言常见3种排序
java·c语言·开发语言·c++·算法·c#·排序算法
百度Geek说1 小时前
前沿多模态模型开发与应用实战3:DeepSeek-VL2多模态理解大模型算法解析与功能抢先体验
算法
小王努力学编程1 小时前
动态规划学习——回文子串系列问题【C++】
c++·学习·算法·leetcode·动态规划
ZTLJQ2 小时前
基于机器学习的三国时期诸葛亮北伐失败因素量化分析
人工智能·算法·机器学习