python解决8皇后问题

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) 这行代码用于构建一个字符串,表示当前行的皇

你可能感兴趣的:(算法,python,开发语言,前端)