python八皇后代码
时间: 2024-10-21 18:00:49 浏览: 33
八皇后python解法
在Python中,解决八皇后问题通常采用回溯法。这是一种递归算法,用于尝试在8x8的国际象棋棋盘上放置八个皇后,同时保证任意两个皇后之间都不会在同一行、同一列或对角线上。以下是简单的八皇后问题的Python代码:
```python
def solve_n_queens(n):
def is_safe(board, row, col):
# 检查行、列和左上到右下的对角线是否有冲突
for i in range(col):
if board[row][i] == 1 or \
board[i][col] == 1 or \
(row - i) == (board[row][col] - col):
return False
return True
def place_queen(board, row):
if row >= n:
solutions.append([board[i] for i in range(n)])
else:
for col in range(n):
if is_safe(board, row, col):
board[row][col] = 1
place_queen(board, row + 1)
board[row][col] = 0 # 回溯,恢复位置
solutions = []
board = [0] * n
place_queen(board, 0)
return solutions
# 调用函数并打印解决方案
n_queens_solutions = solve_n_queens(8)
for solution in n_queens_solutions:
print(solution)
阅读全文