AcWing 843. n-皇后问题
原题链接
中等
def main():
n = int(input())
res = []
dfs(n, [], res)
for p in res:
for i in p:
print ('.' * i + 'Q' + (n - i - 1) * '.')
print()
def dfs(n, cols, res):
row = len(cols) # 第0行开始
if row == n:
res.append(list(cols))
for col in range(n): # 0, 0 开始
if not is_valid(cols, col, row):
continue
cols.append(col)
dfs(n, cols, res)
cols.pop()
def is_valid(cols, col, row):
for r, c in enumerate(cols):
if c == col:
return False
if r + c == col + row or r - c == row - col:
return False
return True
main()