八皇后问题python代码
时间: 2023-10-13 19:25:02 浏览: 84
以下是八皇后问题的Python代码:
```python
def is_valid(board, row, col, n):
# check row on left side
for i in range(col):
if board[row][i] == 1:
return False
# check upper diagonal on left side
for i, j in zip(range(row, -1, -1), range(col, -1, -1)):
if board[i][j] == 1:
return False
# check lower diagonal on left side
for i, j in zip(range(row, n, 1), range(col, -1, -1)):
if board[i][j] == 1:
return False
return True
def solve_n_queens(board, col, n):
if col == n:
return True
for i in range(n):
if is_valid(board, i, col, n):
board[i][col] = 1
if solve_n_queens(board, col + 1, n):
return True
board[i][col] = 0
return False
def print_solution(board, n):
for i in range(n):
for j in range(n):
print(board[i][j], end=" ")
print()
def solve(n):
board = [[0 for x in range(n)] for y in range(n)]
if not solve_n_queens(board, 0, n):
print("Solution does not exist")
return False
print_solution(board, n)
return True
# test the function
solve(8)
```
这个程序使用回溯算法解决八皇后问题。它首先定义了一个`is_valid()`函数,用于检查当前皇后的位置是否是有效的。然后,它使用`solve_n_queens()`函数递归地放置皇后,并在每个位置上检查是否是有效的。最后,它使用`print_solution()`函数打印出解决方案。最后,它在`solve()`函数中调用这些函数来解决八皇后问题。
阅读全文