其他分享
首页 > 其他分享> > LeetCode 36. 有效的数独

LeetCode 36. 有效的数独

作者:互联网

我的LeetCode:https://leetcode-cn.com/u/ituring/

我的LeetCode刷题源码[GitHub]:https://github.com/izhoujie/Algorithmcii

LeetCode 36. 有效的数独

题目

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

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

上图是一个部分填充的有效的数独。

数独部分空格内已填入了数字,空白格用 '.' 表示。

示例 1:

输入:
[
  ["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:

输入:
[
  ["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 存在, 因此这个数独是无效的。

说明:

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/valid-sudoku
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

这道题做出来是比较简单的,暴力来每行每竖每小宫格分别校验就可以了,这样看至少需要三次全扫描;
如何做到只扫描一遍就能完成呢?分析后可能发现比较难解决是小宫格的索引问题,其次如果要保存原始数据,应该需要
横竖小宫格共三个二维数组(或者set集合),但是我们只需要直到1-9有还是没有对应的就是0和1,因此可以进一步压缩二维数组为一位数组,
每个数组的int的前9个bit位用来存储1-9是否出现过,综上,从需要三次扫描三个二维数组和一次扫描三个二维数组和一次扫描
一个二维数组,算法的效率提升是非常明显的;

思路1-三遍扫描,横竖小宫格各自作校验

步骤:

  1. 新建三个set对应横竖小宫格;
  2. 三次扫描分别校验横竖小宫格;

思路2-只扫描一次

只扫描一次的关键是定位小宫格的索引:
关键点小宫格的索引 = (i/3)3 + j/3 ;
可以这么理解:
- i/3表示第几行的小宫格,取值为0、1、2对应实际的第一、二、三行;
- (i/3)

标签:数字,扫描,36,数组,LeetCode,数独,宫格
来源: https://www.cnblogs.com/izhoujie/p/12629853.html