Re: [閒聊] 每日LeetCode

作者: pandix (麵包屌)   2022-11-23 11:19:37
※ 引述《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
作者: Rushia (みけねこ的鼻屎)   2022-11-23 11:23:00
大師

Links booklink

Contact Us: admin [ a t ] ucptt.com