N皇后问题:溯搜索算法完整python代码
时间: 2024-12-21 15:11:18 浏览: 11
N皇后问题是经典的回溯法问题,它涉及在一个n×n的棋盘上放置n个皇后,使得任意两个皇后都不会在同一行、同一列,以及对角线上。以下是使用Python实现的完整溯搜索算法:
```python
def is_safe(board, row, col):
# 检查列是否冲突
for i in range(row):
if board[i] == col:
return False
# 检查左上方对角线是否冲突
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i] == j:
return False
# 检查右上方对角线是否冲突
for i, j in zip(range(row, n, 1), range(col, n, 1)):
if board[i] == j:
return False
return True
def solve_n_queens(n):
def place_queen(board, col):
if col >= n:
solutions.append(list(board))
return
for row in range(n):
if is_safe(board, row, col):
board[row] = col
place_queen(board, col + 1)
board[row] = -1
board = [-1] * n
solutions = []
place_queen(board, 0)
return solutions
# 测试代码
n = 4
solutions = solve_n_queens(n)
for solution in solutions:
print(solution)
阅读全文