n = 4 # 以4皇后举例
result = []
# 放置互斥的列、左斜线、右斜线信息
cols= set()
pie = set()
na = set()
def dfs(row, state):
if row >= n:
result.append(state)
for col in range(n):
if col in cols or row + col in pie or row - col in na:
continue
cols.add(col)
pie.add(row + col)
na.add(row - col)
dfs(row + 1 , state + [col])
cols.remove(col)
pie.remove(row + col)
na.remove(row - col)
def generate_result():
board = []
for data in result:
for i in data:
board.append("." * i + "Q"+"."*(n-i-1))
return [board[i:i+n] for i in range(0,len(board),n)]
dfs(0,[])
print(generate_result())
原文地址:https://www.cnblogs.com/yeni/p/11613072.html
时间: 2024-10-07 05:02:30