@@ -366,40 +366,56 @@ class Solution:
366366 """
367367 Do not return anything, modify board in-place instead.
368368 """
369- self .backtracking(board)
370-
371- def backtracking (self , board : List[List[str ]]) -> bool :
372- # 若有解,返回True;若无解,返回False
373- for i in range (len (board)): # 遍历行
374- for j in range (len (board[0 ])): # 遍历列
375- # 若空格内已有数字,跳过
376- if board[i][j] != ' .' : continue
377- for k in range (1 , 10 ):
378- if self .is_valid(i, j, k, board):
379- board[i][j] = str (k)
380- if self .backtracking(board): return True
381- board[i][j] = ' .'
382- # 若数字1-9都不能成功填入空格,返回False无解
383- return False
384- return True # 有解
385-
386- def is_valid (self , row : int , col : int , val : int , board : List[List[str ]]) -> bool :
387- # 判断同一行是否冲突
388- for i in range (9 ):
389- if board[row][i] == str (val):
390- return False
391- # 判断同一列是否冲突
392- for j in range (9 ):
393- if board[j][col] == str (val):
394- return False
395- # 判断同一九宫格是否有冲突
396- start_row = (row // 3 ) * 3
397- start_col = (col // 3 ) * 3
398- for i in range (start_row, start_row + 3 ):
399- for j in range (start_col, start_col + 3 ):
400- if board[i][j] == str (val):
401- return False
402- return True
369+ row_used = [set () for _ in range (9 )]
370+ col_used = [set () for _ in range (9 )]
371+ box_used = [set () for _ in range (9 )]
372+ for row in range (9 ):
373+ for col in range (9 ):
374+ num = board[row][col]
375+ if num == " ." :
376+ continue
377+ row_used[row].add(num)
378+ col_used[col].add(num)
379+ box_used[(row // 3 ) * 3 + col // 3 ].add(num)
380+ self .backtracking(0 , 0 , board, row_used, col_used, box_used)
381+
382+ def backtracking (
383+ self ,
384+ row : int ,
385+ col : int ,
386+ board : List[List[str ]],
387+ row_used : List[List[int ]],
388+ col_used : List[List[int ]],
389+ box_used : List[List[int ]],
390+ ) -> bool :
391+ if row == 9 :
392+ return True
393+
394+ next_row, next_col = (row, col + 1 ) if col < 8 else (row + 1 , 0 )
395+ if board[row][col] != " ." :
396+ return self .backtracking(
397+ next_row, next_col, board, row_used, col_used, box_used
398+ )
399+
400+ for num in map (str , range (1 , 10 )):
401+ if (
402+ num not in row_used[row]
403+ and num not in col_used[col]
404+ and num not in box_used[(row // 3 ) * 3 + col // 3 ]
405+ ):
406+ board[row][col] = num
407+ row_used[row].add(num)
408+ col_used[col].add(num)
409+ box_used[(row // 3 ) * 3 + col // 3 ].add(num)
410+ if self .backtracking(
411+ next_row, next_col, board, row_used, col_used, box_used
412+ ):
413+ return True
414+ board[row][col] = " ."
415+ row_used[row].remove(num)
416+ col_used[col].remove(num)
417+ box_used[(row // 3 ) * 3 + col // 3 ].remove(num)
418+ return False
403419```
404420
405421### Go
0 commit comments