1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| import copy class Solution: def solveNQueens(self, n: int) -> List[List[str]]: nums = [ [ '.' for _ in range(n)] for _ in range(n) ] result = [] def check_legal(nums,row,col) ->bool: for i in range(0,row): if nums[i][col]=="Q": return False i,j = row-1,col-1 while i>=0 and j>=0: if nums[i][j]=="Q": return False i -= 1 j -= 1 i,j = row-1,col+1 while i>=0 and j<=n-1: if nums[i][j]=="Q": return False i -= 1 j += 1 return True def split_tree(nums,row=0)->List[List[str]]: if row==n: return result.append(copy.deepcopy(nums)) for j in range(0,n): if check_legal(nums,row,j)==False: continue nums[row][j] = "Q" split_tree(nums,row+1) nums[row][j] = "."
for values in result: for index,value in list(enumerate(values)): values[index] = ''.join(value) return result return split_tree(nums,0)
|