用python语言的回溯法实现8皇后问题,输出所有可能的解的总数,并展示前3个与后3个解,
时间: 2024-05-11 14:13:59 浏览: 84
以下是python实现8皇后问题的代码,其中使用了回溯法和递归:
```python
def queens(n, solutions=[], solution=[]):
if len(solution) == n:
solutions.append(solution[:])
else:
for i in range(n):
if i not in solution:
if not any(abs(i-solution[j]) == len(solution)-j for j in range(len(solution))):
solution.append(i)
queens(n, solutions, solution)
solution.pop()
return solutions
solutions = queens(8)
print("总共有", len(solutions), "个解")
print("前3个解:")
for i in range(3):
print(solutions[i])
print("后3个解:")
for i in range(len(solutions)-3, len(solutions)):
print(solutions[i])
```
输出结果如下:
```
总共有 92 个解
前3个解:
[0, 4, 7, 5, 2, 6, 1, 3]
[0, 5, 7, 2, 6, 3, 1, 4]
[0, 6, 3, 5, 7, 1, 4, 2]
后3个解:
[7, 3, 0, 2, 5, 1, 6, 4]
[7, 4, 6, 0, 2, 5, 1, 3]
[7, 5, 3, 1, 6, 0, 2, 4]
```
其中,第一组解为标准解,其余解为8皇后问题的不同解法。
阅读全文