Determine if a 9x9 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 9
3x3
sub-boxes of the grid must contain the digits1-9
without repetition.
A partially filled sudoku which is valid.
The Sudoku board could be partially filled, where empty cells are filled with the character '.'
.
Example 1:
Input: [ ["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"] ] Output: true
一道判断表格是否符合数独规则的题。
可以用一个final做记录,对于每一个数字(非“.”)的话,就对这个数字所在行,所在列,所在九宫格做记录。
需要注意的是这里temp代表的是字符串而非数字,所以不会出错。
(5,“6“)代表第五行有6,(”5“,6)代表第六列有5。
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
final=set()
l=len(board)
for i in range(l):
for j in range(l):
temp=board[i][j]
if temp!='.':
if (i,temp) in final or (temp,j) in final or (i//3,j//3,temp) in final:
return False
final.add((i,temp))
final.add((temp,j))
final.add((i//3, j//3, temp))
return True