def is_valid(queens, row, col):
for i in range(row):
if queens[i] == col or abs(queens[i] - col) == abs(i - row):
return False
return True
def solve_n_queens(n, row, queens, result):
if row == n:
result.append(queens[:]) # 将当前解添加到结果中
return
for col in range(n):
if is_valid(queens, row, col):
queens[row] = col
solve_n_queens(n, row + 1, queens, result)
queens[row] = -1 # 回溯
def n_queens(n):
result = []
queens = [-1] * n # 初始化皇后位置为-1
solve_n_queens(n, 0, queens, result)
return result
# 测试
n = 8 # 8皇后问题
solutions = n_queens(n)
for solution in solutions:
for col in solution:
row_str = '.' * col + 'Q' + '.' * (n - col - 1)
print(row_str)
print()
row_str = ‘.’ * col + ‘Q’ + ‘.’ * (n - col - 1) 这行代码用于构建一个字符串,表示当前行的皇文章来源地址https://www.toymoban.com/news/detail-646870.html
文章来源:https://www.toymoban.com/news/detail-646870.html
到了这里,关于python解决8皇后问题的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!