leetcode 36. 有效的数独 Python

描述

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

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

leetcode 36. 有效的数独 Python_第1张图片
上图是一个部分填充的有效的数独。

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

示例 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的小方格有点麻烦
但是转换一下思路,就都变成一样的,需要确定0-8行9个数字只出现1次,0-8列9个数字最多只出现一次,同样,0-8个小方块也是9个数字最多出现一次
行和列的遍历是容易的,关键是怎样同时还遍历小方块,
观察观察可以发现,横着三个小方块,三组,如果按0-8编号的话,它们的编号满足i/3*3+j/3,i表示对行的遍历,j表示对列的遍历,/表示取整的除法,第一组i,j均<=2,所以结果是编号0,第二组i<=2;3<=j<6,所以计算的编号为1,依次类推
分别用row[i][num], col[j][num]和box[index][num]来表示第i行的数字num、第j行的数字num、第index个小方块的数字num是否已经出现过,代码如下

代码

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        row = [[False for _ in range(1, 11)] for _ in range(0, 9)]
        col = [[False for _ in range(1, 11)] for _ in range(0, 9)]
        box = [[False for _ in range(1, 11)] for _ in range(0, 9)]
        # print(row)
        # print(col)
        for i in range(0, 9):
            for j in range(0, 9):
                    num = i//3*3 + j//3
                    c = board[i][j]
                # for c in board[i]:
                    if c is not '.':
                        if row[i][int(c)] is True:
                            return False
                        if col[j][int(c)] is True:
                            return False
                        if box[num][int(c)] is True:
                            return False
                        row[i][int(c)] = True
                        col[j][int(c)] = True
                        box[num][int(c)] = True
        return True

你可能感兴趣的:(算法,leetcode)