簡單來說就是為給一個二維陣列,請確定給的二維陣列是合法的數獨矩陣。
範例:
組合檢查
class Solution:
def isValidSudoku(self, board: List[List[str]]) -> bool:
"""
Let's keep tracking each element and see where they belong
"""
# Initialize tackers for each row, column and box
row = {i: [] for i in range(9)}
col = {i: [] for i in range(9)}
box = {i: [] for i in range(9)}
for row_idx in range(9):
for col_idx in range(9):
e = board[row_idx][col_idx]
box_idx = (row_idx // 3) * 3
box_idx += col_idx // 3
if e == '.':
continue
if e in row[row_idx] or e in col[col_idx] or e in box[box_idx]:
return False
else:
row[row_idx].append(e)
col[col_idx].append(e)
box[box_idx].append(e)
return True
這邊主要是我們會有三個檢查的分組,首先我們先產生該分組:
row: {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: []}
col: {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: []}
box: {0: [], 1: [], 2: [], 3: [], 4: [], 5: [], 6: [], 7: [], 8: []}
基本上裡面各個list之中不能有重複的數字:
所以我們只要能在遞迴時,知道每個數字應該在哪些分組,即可完成。
橫的跟直的都非常容易離解,如拆開來看會像是:
for row_idx in range(9):
for col_idx in range(9):
e = board[row_idx][col_idx]
if e == '.':
continue
if e in row[row_idx]:
return False
else:
row[row_idx].append(e)
for row_idx in range(9):
for col_idx in range(9):
e = board[row_idx][col_idx]
if e == '.':
continue
if e in col[col_idx]:
return False
else:
col[col_idx].append(e)
箱型檢查則是使用了位置的idx進行分組,如拆開來看會像是:
for row_idx in range(9):
for col_idx in range(9):
e = board[row_idx][col_idx]
box_idx = (row_idx // 3) * 3
box_idx += col_idx // 3
if e == '.':
continue
if e in box[box_idx]:
return False
else:
box[box_idx].append(e)
return True
位置的idx會是這樣
1.
0 + 0 = 0
0 + 0 = 0
0 + 0 = 0
0 + 1 = 1
0 + 1 = 1
0 + 1 = 1
0 + 2 = 2
0 + 2 = 2
0 + 2 = 2
0 + 0 = 0
0 + 0 = 0
0 + 0 = 0
0 + 1 = 1
0 + 1 = 1
0 + 1 = 1
0 + 2 = 2
0 + 2 = 2
0 + 2 = 2
0 + 0 = 0
0 + 0 = 0
0 + 0 = 0
0 + 1 = 1
0 + 1 = 1
0 + 1 = 1
0 + 2 = 2
0 + 2 = 2
0 + 2 = 2
2.
3 + 0 = 3
3 + 0 = 3
3 + 0 = 3
3 + 1 = 4
3 + 1 = 4
3 + 1 = 4
3 + 2 = 5
3 + 2 = 5
3 + 2 = 5
3 + 0 = 3
3 + 0 = 3
3 + 0 = 3
3 + 1 = 4
3 + 1 = 4
3 + 1 = 4
3 + 2 = 5
3 + 2 = 5
3 + 2 = 5
3 + 0 = 3
3 + 0 = 3
3 + 0 = 3
3 + 1 = 4
3 + 1 = 4
3 + 1 = 4
3 + 2 = 5
3 + 2 = 5
3 + 2 = 5
3.
6 + 0 = 6
6 + 0 = 6
6 + 0 = 6
6 + 1 = 7
6 + 1 = 7
6 + 1 = 7
6 + 2 = 8
6 + 2 = 8
6 + 2 = 8
6 + 0 = 6
6 + 0 = 6
6 + 0 = 6
6 + 1 = 7
6 + 1 = 7
6 + 1 = 7
6 + 2 = 8
6 + 2 = 8
6 + 2 = 8
6 + 0 = 6
6 + 0 = 6
6 + 0 = 6
6 + 1 = 7
6 + 1 = 7
6 + 1 = 7
6 + 2 = 8
6 + 2 = 8
6 + 2 = 8
如果覺得合在一起難以理解,可以參考