36. Valid Sudoku

Posted king-lps

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了36. Valid Sudoku相关的知识,希望对你有一定的参考价值。

1. 原始题目

判断一个 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 形式的。

 

2. 思路

既然要针对三个模块查重,那么就分别建立三个模块(行、列、box)。每个模块都应该有9个哈希表和集合。按照行列一次循环就可以解决问题。

 

3. 解法

 1 class Solution:
 2     def isValidSudoku(self, board: List[List[str]]) -> bool:
 3         row = [{} for i in range(9)]         # 行集合 9行
 4         column = [{} for i in range(9)]      # 列集合 9列
 5         box = [{} for i in range(9)]         # 宫格集合 3*3=9个宫格
 6         
 7         for i in range(9):
 8             for j in range(9):
 9                 if board[i][j]!=.:         # 是数字则循环
10                     num = int(board[i][j])
11                     row[i][num] = row[i].get(num,0) + 1        # 在当前行里添加
12                     column[j][num] =column[j].get(num,0) + 1   # 在当前列里添加 
13                     box[int(i//3)*3+int(j//3)][num] = box[int(i//3)*3+int(j//3)].get(num,0)+ 1  # 在当前宫格内添加
14                     
15                     if row[i][num]>1 or column[j][num]>1 or box[int(i//3)*3+int(j//3)][num]>1:  # 若再次出现则返回false
16                         return False
17         return True

 

以上是关于36. Valid Sudoku的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode-36. Valid Sudoku

[LeetCode] 36. Valid Sudoku

[leetcode-36-Valid Sudoku]

leetcode36. Valid Sudoku

36. Valid Sudoku

36. Valid Sudoku