簡單來說就是為給一個二維陣列,請確定給的二維陣列是合法的數獨矩陣。
範例:
分段檢查
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
# row validation
for row in board:
seen = dict()
for i in row:
if i == ".":
continue
if i not in seen:
seen[i] = True
else:
return False
# column validation
for col in range(len(board)):
seen = dict()
for row in range(len(board)):
if board[row][col] == ".":
continue
if board[row][col] not in seen:
seen[board[row][col]] = True
else:
return False
# box validations
for group in [(0,1,2),(3,4,5),(6,7,8)]:
d1 = {}
d2 = {}
d3 = {}
for row in group:
for col in range(len(board)):
key = board[row][col]
if key == ".":
continue
if col < 3:
if key not in d1:
d1[key] = True
else:
return False
elif col < 6:
if key not in d2:
d2[key] = True
else:
return False
else:
if key not in d3:
d3[key] = True
else:
return False
return True
這個方法,我們分成三個部分來檢查是否是合法的數獨:
橫的檢查
# row validation
for row in board:
seen = dict()
for i in row:
if i == ".":
continue
if i not in seen:
seen[i] = True
else:
return False
直的檢查
# column validation
for col in range(len(board)):
seen = dict()
for row in range(len(board)):
if board[row][col] == ".":
continue
if board[row][col] not in seen:
seen[board[row][col]] = True
else:
return False
箱型檢查
最後這個比較難,箱型檢查。概念主要是,先由上而下,每三個分成一組,最後再將每組切成三個部分進行檢查。
# box validations
for group in [(0,1,2),(3,4,5),(6,7,8)]:
d1 = {}
d2 = {}
d3 = {}
for row in group:
for col in range(len(board)):
key = board[row][col]
if key == ".":
continue
if col < 3:
if key not in d1:
d1[key] = True
else:
return False
elif col < 6:
if key not in d2:
d2[key] = True
else:
return False
else:
if key not in d3:
d3[key] = True
else:
return False
如果覺得分段程式碼太長,這邊提供組合起來的。