回溯
没看答案,labuladong永远嘀神!!
python
class Solution:
def solveNQueens(self, n: int):
track = []
res = []
def backtrack(raw):
nonlocal n
if len(track) == n:
pan = []
for i in range(n):
s = ['.'] * n
s[track[i]] = 'Q'
pan.append(''.join(s))
res.append(pan)
return
# 按行做选择,所以皇后一定不同行了
for col in range(n):
# 皇后不能同列
if col in track:
continue
# 判断斜线
if raw != 0:
tmp = 0 # 不在同一斜线上的皇后数量
for j in range(raw):
# 存在同一斜线上的皇后
if abs(track[j]-col) == abs(j-raw):
if track[j] == 0 and col == n-1:
tmp += 1
else:
break
tmp += 1
if tmp != raw:
continue
track.append(col)
raw += 1
backtrack(raw)
raw -= 1
track.pop()
backtrack(0)
return res