mirror of
https://github.com/youngyangyang04/leetcode-master.git
synced 2025-07-06 07:06:42 +08:00
现有解法python超时,通过减少递归次数优化
This commit is contained in:
@ -366,40 +366,56 @@ class Solution:
|
||||
"""
|
||||
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:
|
||||
# 若有解,返回True;若无解,返回False
|
||||
for i in range(len(board)): # 遍历行
|
||||
for j in range(len(board[0])): # 遍历列
|
||||
# 若空格内已有数字,跳过
|
||||
if board[i][j] != '.': continue
|
||||
for k in range(1, 10):
|
||||
if self.is_valid(i, j, k, board):
|
||||
board[i][j] = str(k)
|
||||
if self.backtracking(board): return True
|
||||
board[i][j] = '.'
|
||||
# 若数字1-9都不能成功填入空格,返回False无解
|
||||
return False
|
||||
return True # 有解
|
||||
def backtracking(
|
||||
self,
|
||||
row: int,
|
||||
col: int,
|
||||
board: List[List[str]],
|
||||
row_used: List[List[int]],
|
||||
col_used: List[List[int]],
|
||||
box_used: List[List[int]],
|
||||
) -> bool:
|
||||
if row == 9:
|
||||
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
|
||||
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
|
||||
|
Reference in New Issue
Block a user