利用python分别采用递归和迭代两种算法解决八皇后问题,
时间: 2023-06-27 16:05:29 浏览: 111
八皇后问题是一个经典的回溯算法问题,其目标是在一个8×8的棋盘上放置8个皇后,使得任意两个皇后都不能处于同一行、同一列或同一斜线上。
递归实现八皇后问题:
```python
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return False
def queens(num=8, state=()):
for pos in range(num):
if not conflict(state, pos):
if len(state) == num-1:
yield (pos,)
else:
for result in queens(num, state+(pos,)):
yield (pos,)+result
for solution in queens():
print(solution)
```
迭代实现八皇后问题:
```python
def queens(num=8):
solutions = [(pos,) for pos in range(num)]
for i in range(num-1):
solutions = [solution+(pos,)
for solution in solutions
for pos in range(num)
if not conflict(solution, pos)]
return solutions
def conflict(state, nextX):
nextY = len(state)
for i in range(nextY):
if abs(state[i]-nextX) in (0, nextY-i):
return True
return False
for solution in queens():
print(solution)
```
以上两种算法都可以求出八皇后问题的解,但递归算法更加简洁易懂,而迭代算法则更加直观易懂。
阅读全文