python深度优先算法 八皇后剪枝_使用深度优先+递归+剪枝解决八皇后问题

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())

你可能感兴趣的:(python深度优先算法,八皇后剪枝)