※ 引述《Rushia (みけねこ的鼻屎)》之铭言:
: 36. Valid Sudoku
: 给你一个二维字符阵列表示一个数独,包含1~9和表示空白的.字符,一个合法数独
: 满足以下条件:
: 1.每行和每列最多出现一种数字一次
: 2.一个3x3九宫格内只会出现一种数字一次
: 3.数独可能无解(无法填满数字),但是只有满足1或2才是Invalid
: 判断给定的棋盘是否是一个合法数独
: Example:
: https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Sudoku-by-L2G-20050714.svg/250px-Sudoku-by-L2G-20050714.svg.png
: Input: board =
: [["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
思路:
1. 每个直排/横排/九宫格都开一个 set 去记
检查数字有没有在自己属于的 set 里出现过
牺牲了一点空间
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
vset = [set() for i in range(9)]
hset = [set() for i in range(9)]
bset = [[set() for i in range(3)] for j in range(3)]
for i in range(9):
for j in range(9):
if board[i][j] == '.':
continue
elif board[i][j] in vset[i] or board[i][j] in hset[j] or
board[i][j] in bset[i//3][j//3]:
return False
else:
vset[i].add(board[i][j])
hset[j].add(board[i][j])
bset[i//3][j//3].add(board[i][j])
return True