Merge pull request #2851 from Tony-Idle/0037

0037 解数独 现有解法python超时,通过减少递归次数优化
This commit is contained in:
程序员Carl
2024-12-12 09:01:15 +08:00
committed by GitHub

View File

@ -366,40 +366,56 @@ class Solution:
""" """
Do not return anything, modify board in-place instead. Do not return anything, modify board in-place instead.
""" """
self.backtracking(board) row_used = [set() for _ in range(9)]
col_used = [set() for _ in range(9)]
box_used = [set() for _ in range(9)]
for row in range(9):
for col in range(9):
num = board[row][col]
if num == ".":
continue
row_used[row].add(num)
col_used[col].add(num)
box_used[(row // 3) * 3 + col // 3].add(num)
self.backtracking(0, 0, board, row_used, col_used, box_used)
def backtracking(self, board: List[List[str]]) -> bool: def backtracking(
# 若有解返回True若无解返回False self,
for i in range(len(board)): # 遍历行 row: int,
for j in range(len(board[0])): # 遍历列 col: int,
# 若空格内已有数字,跳过 board: List[List[str]],
if board[i][j] != '.': continue row_used: List[List[int]],
for k in range(1, 10): col_used: List[List[int]],
if self.is_valid(i, j, k, board): box_used: List[List[int]],
board[i][j] = str(k) ) -> bool:
if self.backtracking(board): return True if row == 9:
board[i][j] = '.'
# 若数字1-9都不能成功填入空格返回False无解
return False
return True # 有解
def is_valid(self, row: int, col: int, val: int, board: List[List[str]]) -> bool:
# 判断同一行是否冲突
for i in range(9):
if board[row][i] == str(val):
return False
# 判断同一列是否冲突
for j in range(9):
if board[j][col] == str(val):
return False
# 判断同一九宫格是否有冲突
start_row = (row // 3) * 3
start_col = (col // 3) * 3
for i in range(start_row, start_row + 3):
for j in range(start_col, start_col + 3):
if board[i][j] == str(val):
return False
return True return True
next_row, next_col = (row, col + 1) if col < 8 else (row + 1, 0)
if board[row][col] != ".":
return self.backtracking(
next_row, next_col, board, row_used, col_used, box_used
)
for num in map(str, range(1, 10)):
if (
num not in row_used[row]
and num not in col_used[col]
and num not in box_used[(row // 3) * 3 + col // 3]
):
board[row][col] = num
row_used[row].add(num)
col_used[col].add(num)
box_used[(row // 3) * 3 + col // 3].add(num)
if self.backtracking(
next_row, next_col, board, row_used, col_used, box_used
):
return True
board[row][col] = "."
row_used[row].remove(num)
col_used[col].remove(num)
box_used[(row // 3) * 3 + col // 3].remove(num)
return False
``` ```
### Go ### Go