广度优先搜索n皇后问题python代码
时间: 2023-10-12 17:20:06 浏览: 94
基于python实现的广度优先遍历搜索(BFS)实验源码+代码详细注释+项目说明+实验结果及总结.7z
5星 · 资源好评率100%
以下是广度优先搜索解决n皇后问题的Python代码:
```python
from queue import Queue
def is_valid(board, row, col):
for i in range(row):
if board[i] == col or \
abs(board[i] - col) == abs(i - row):
return False
return True
def bfs(n):
q = Queue()
q.put([])
while not q.empty():
board = q.get()
if len(board) == n:
return board
for i in range(n):
if is_valid(board, len(board), i):
q.put(board + [i])
def print_board(board):
for row in board:
line = ""
for col in range(len(board)):
if col == row:
line += "Q "
else:
line += ". "
print(line)
n = 8
board = bfs(n)
print_board(board)
```
该代码使用队列实现广度优先搜索算法,每次取出一个棋盘,检查其是否合法,如果合法就将其所有可能的下一步棋盘加入队列中。当棋盘长度为n时,返回该棋盘。最后打印出解决方案。
阅读全文