python解决拉斯维加斯算法求n皇后问题,并输出结果
时间: 2024-02-02 08:03:38 浏览: 91
这里提供一个Python解决n皇后问题的拉斯维加斯算法实现,代码如下:
```python
import random
def n_queens(n):
board = [-1] * n
attempts = 0
while True:
col = random.randint(0, n-1)
row = find_available_row(col, board)
if row is not None:
board[col] = row
if col == n-1:
return board
else:
board[col] = -1
attempts += 1
if attempts > 3 * n:
board = [-1] * n
attempts = 0
def find_available_row(col, board):
n = len(board)
rows = list(range(n))
random.shuffle(rows)
for row in rows:
if is_safe(row, col, board):
return row
return None
def is_safe(row, col, board):
for c, r in enumerate(board):
if r == row or c-r == col-row or c+r == col+row:
return False
return True
n = 8
board = n_queens(n)
if board is not None:
for row in board:
line = ['.'] * n
line[row] = 'Q'
print(' '.join(line))
else:
print('Failed to find a solution.')
```
该算法思想是随机选择一个列,然后在该列中随机选择一个行放置皇后,如果该位置不安全,则重新选择。如果找到了合法的皇后布局,则返回结果。如果多次尝试后仍然没有找到合法的皇后布局,则重新开始。该算法的时间复杂度是O(n!),但是由于随机性使得其在实际运行中的效率和表现比较好。
阅读全文