LeetCode 有效的数独

有效的数独

 

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

 

思路:采用最朴素的策略,分别检查行,列,3*3矩阵

 

 

 1 class Solution(object):
 2     def isValidSudoku(self, board):
 3         """
 4         :type board: List[List[str]]
 5         :rtype: bool
 6         """
 7         #deal with hang
 8         for line in board:
 9             temp = set()
10             for item in line:
11                 if item == '.':
12                     continue
13                 if item in temp:
14                     return False
15                 else:
16                     temp.add(item)
17         #deal with lie
18         index_range = range(9)
19         for index in index_range:
20             temp = set()
21             for line in board:
22                 if line[index] == '.':
23                     continue
24                 if line[index] in temp:
25                     return False
26                 else:
27                     temp.add(line[index])
28         #deal with 3*3
29         hang=[0,3,6]
30         lie=[0,3,6]
31         for i1 in hang:
32             for i2 in lie:
33                 temp = set()
34                 for i3 in range(3):
35                     for i4 in range(3):
36                         if board[i3+i1][i4+i2] == '.':
37                             continue
38                         if board[i3+i1][i4+i2] in temp:
39                             return False
40                         else:
41                             temp.add(board[i3+i1][i4+i2])
42         return True

 

posted @ 2018-09-11 21:58  gremount  阅读(138)  评论(0编辑  收藏  举报