leetcode题解之36. 有效的数独

Posted 刷题之路1

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 存在, 因此这个数独是无效的。

说明:

  • 一个有效的数独(部分已被填充)不一定是可解的。
  • 只需要根据以上规则,验证已经填入的数字是否有效即可。
  • 给定数独序列只包含数字 1-9 和字符 ‘.‘ 。
  • 给定数独永远是 9x9 形式的。

思路

一个简单的解决方案是遍历该 9 x 9 数独 次,以确保:

  • 行中没有重复的数字。
  • 列中没有重复的数字。
  • 3 x 3 子数独内没有重复的数字。

实际上,所有这一切都可以在一次迭代中完成。


方法:一次迭代

首先,让我们来讨论下面两个问题:

  • 如何枚举子数独?

可以使用 box_index = (row / 3) * 3 + columns / 3,其中 / 是整数除法。

技术图片

  • 如何确保行 / 列 / 子数独中没有重复项?

可以利用 value -> count 哈希映射来跟踪所有已经遇到的值。

现在,我们完成了这个算法的所有准备工作:

  • 遍历数独。
  • 检查看到每个单元格值是否已经在当前的行 / 列 / 子数独中出现过:
    • 如果出现重复,返回 false
    • 如果没有,则保留此值以进行进一步跟踪。
  • 返回 true

技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片技术图片
1 / 15

class Solution {
  public boolean isValidSudoku(char[][] board) {
    // init data
    HashMap<Integer, Integer> [] rows = new HashMap[9];
    HashMap<Integer, Integer> [] columns = new HashMap[9];
    HashMap<Integer, Integer> [] boxes = new HashMap[9];
    for (int i = 0; i < 9; i++) {
      rows[i] = new HashMap<Integer, Integer>();
      columns[i] = new HashMap<Integer, Integer>();
      boxes[i] = new HashMap<Integer, Integer>();
    }
<span class="hljs-comment">// validate a board</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">9</span>; i++) {
  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">0</span>; j &lt; <span class="hljs-number">9</span>; j++) {
    <span class="hljs-keyword">char</span> num = board[i][j];
    <span class="hljs-keyword">if</span> (num != <span class="hljs-string">‘.‘</span>) {
      <span class="hljs-keyword">int</span> n = (<span class="hljs-keyword">int</span>)num;
      <span class="hljs-keyword">int</span> box_index = (i / <span class="hljs-number">3</span> ) * <span class="hljs-number">3</span> + j / <span class="hljs-number">3</span>;

      <span class="hljs-comment">// keep the current cell value</span>
      rows[i].put(n, rows[i].getOrDefault(n, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>);
      columns[j].put(n, columns[j].getOrDefault(n, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>);
      boxes[box_index].put(n, boxes[box_index].getOrDefault(n, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>);

      <span class="hljs-comment">// check if this value has been already seen before</span>
      <span class="hljs-keyword">if</span> (rows[i].get(n) &gt; <span class="hljs-number">1</span> || columns[j].get(n) &gt; <span class="hljs-number">1</span> || boxes[box_index].get(n) &gt; <span class="hljs-number">1</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }
  }
}

<span class="hljs-keyword">return</span> <span class="hljs-keyword">true</span>;

}
}


class Solution:
def isValidSudoku(self, board):
"""
:type board: List[List[str]]
:rtype: bool
"""

# init data
rows = [{} for i in range(9)]
columns = [{} for i in range(9)]
boxes = [{} for i in range(9)]

    <span class="hljs-comment"># validate a board</span>
    <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(<span class="hljs-number">9</span>):
        <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(<span class="hljs-number">9</span>):
            num = board[i][j]
            <span class="hljs-keyword">if</span> num != <span class="hljs-string">‘.‘</span>:
                num = int(num)
                box_index = (i // <span class="hljs-number">3</span> ) * <span class="hljs-number">3</span> + j // <span class="hljs-number">3</span>
                
                <span class="hljs-comment"># keep the current cell value</span>
                rows[i][num] = rows[i].get(num, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>
                columns[j][num] = columns[j].get(num, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>
                boxes[box_index][num] = boxes[box_index].get(num, <span class="hljs-number">0</span>) + <span class="hljs-number">1</span>
                
                <span class="hljs-comment"># check if this value has been already seen before</span>
                <span class="hljs-keyword">if</span> rows[i][num] &gt; <span class="hljs-number">1</span> <span class="hljs-keyword">or</span> columns[j][num] &gt; <span class="hljs-number">1</span> <span class="hljs-keyword">or</span> boxes[box_index][num] &gt; <span class="hljs-number">1</span>:
                    <span class="hljs-keyword">return</span> <span class="hljs-literal">False</span>         
    <span class="hljs-keyword">return</span> <span class="hljs-literal">True</span>

复杂度分析

  • 时间复杂度:O(1)O(1),因为我们只对 81 个单元格进行了一次迭代。
  • 空间复杂度:O(1)O(1)

https://www.jianshu.com/p/ad0311d97760













以上是关于leetcode题解之36. 有效的数独的主要内容,如果未能解决你的问题,请参考以下文章

算法leetcode|36. 有效的数独(rust重拳出击)

leetcode 36. 有效的数独

《LeetCode之每日一题》:279.有效的数独

《LeetCode之每日一题》:125.有效的数独

leetcode-----36. 有效的数独

Leetcode中等36. 有效的数独JavaScript