【力扣100】51.N皇后 || 斜线判断逻辑
class Solution:
def solveNQueens(self, n: int) -> List[List[str]]:
# 思路是使用递归和回溯,然后判断斜线上是否存放值的逻辑
# 斜线只需要判断左上和右上,因为是一行一行遍历的
col=[0]*n
ans=[]
on_path=[False]*n
left=[False]*(2*n-1)
right=[False]*(2*n-1)
def dfs(r):
if r==n:
ans.append(['.'*c + 'Q' + '.'*(n-c-1) for c in col])
return
for c in range(n):
if not on_path[c] and not left[r+c] and not right[r-c]:
col[r]=c
on_path[c] = left[r+c] = right[r-c] = True
dfs(r+1)
on_path[c] = left[r+c] = right[r-c] = False
dfs(0)
return ans
思路:
- 经典题目,这道题的难点在于斜线判断逻辑