leetcode with python:36. Valid Sudoku

题目:

Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to the following rules:

Each row must contain the digits 1-9 without repetition.
Each column must contain the digits 1-9 without repetition.
Each of the nine 3 x 3 sub-boxes of the grid must contain the digits 1-9 without repetition.

Note:
A Sudoku board (partially filled) could be valid but is not necessarily solvable.
Only the filled cells need to be validated according to the mentioned rules.

给定一个9x9由"1"~"9"和"."组成的二阶矩阵,验证它是不是个数独矩阵,"."表示空白
判断该矩阵是否为数独矩阵标準有几个:
1.每行不会有重複的元素
2.每列不会有重複的元素
3.9个3x3矩阵每个都不会含有重複的元素

为此我们建立了行9个,列9个,3x3矩阵9个
共27个hash set

class Solution:    def isValidSudoku(self, board: List[List[str]]) -> bool:        row=[set() for i in range(9)]        column=[set() for i in range(9)]        block=[set() for i in range(9)]                        for i,m in enumerate(board):            for j,n in enumerate(m):                if n==".":                    continue                if n in row[i] or n in column[j] or  n in block[(i//3)*3+j//3]:                                # (i//3)*3+j//3对9个3x3矩阵做0~8的编号                    return False                            row[i].add(n)                column[j].add(n)                block[(i//3)*3+j//3].add(n)                        return True

遍历所有在该二阶矩阵的元素
"."表空白所以可以直接continue跳过,不必纪录
其他元素纪录在其所在行(j),所在列(i),所在3x3矩阵((i//3) * 3+j//3)代表的set中
一旦发现其所在行,所在列或所在3x3矩阵代表的set
已经有记录该元素,则代表此阵列并非数独矩阵,回传False
而遍历完毕都无回传则回传True
最后执行时间93ms(faster than 98.06%)

那我们下题见


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章