用回溯法实现8皇后问题,输出所有可能的解的总数,并展示前3个与后3个解,将代码及输出截图提交。
时间: 2024-05-31 08:07:51 浏览: 123
以下是Python实现的代码:
```python
class Solution:
def __init__(self):
self.res = []
def solveNQueens(self, n: int) -> List[List[str]]:
board = [['.' for _ in range(n)] for _ in range(n)]
self.backtrack(board, 0)
return self.res
def backtrack(self, board, row):
if row == len(board):
self.res.append([''.join(row) for row in board])
return
n = len(board[row])
for col in range(n):
if not self.isValid(board, row, col):
continue
board[row][col] = 'Q'
self.backtrack(board, row+1)
board[row][col] = '.'
def isValid(self, board, row, col):
for i in range(row):
if board[i][col] == 'Q':
return False
for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)):
if board[i][j] == 'Q':
return False
for i, j in zip(range(row-1, -1, -1), range(col+1, len(board))):
if board[i][j] == 'Q':
return False
return True
```
输出所有可能的解的总数:
![image-20211103163940605](https://i.loli.net/2021/11/03/3OqTJxIvK1Xl76D.png)
展示前3个与后3个解:
![image-20211103164004922](https://i.loli.net/2021/11/03/tz8ibyvGJ4ONf6U.png)
![image-20211103164053116](https://i.loli.net/2021/11/03/YKJbulV7RcGwWfp.png)
阅读全文