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

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())
上一篇:P1328 生活大爆炸版石头剪刀布


下一篇:(二十六)Spring Boot使用@Async实现异步调用:ThreadPoolTaskScheduler线程池的优雅关闭