用python写一个皇后算法
时间: 2024-05-16 07:16:32 浏览: 8
下面是一个用 Python 实现的 N 皇后问题的解法:
```python
def is_valid(board, row, col, n):
"""
Check if a queen can be placed at board[row][col]
"""
for i in range(n):
if board[row][i] == 1 or board[i][col] == 1:
return False
for i in range(n):
for j in range(n):
if (i+j == row+col) or (i-j == row-col):
if board[i][j] == 1:
return False
return True
def solve_n_queens(board, col, n):
"""
Find a solution for N-Queens problem starting from column col
"""
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_board(board):
"""
Print the board
"""
for i in board:
print(i)
def n_queens(n):
"""
Solve N-Queens problem
"""
board = [[0 for x in range(n)] for y in range(n)]
if solve_n_queens(board, 0, n) == False:
print("Solution does not exist")
return False
print_board(board)
return True
n_queens(4)
```
这个算法的基本思想是使用回溯来尝试在每一列中放置皇后。在某个列中放置皇后时,我们检查之前的列和对角线,以确保新的皇后不会被攻击。如果没有找到解决方案,则回溯并尝试其他位置。
相关推荐
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)