回溯法实现8皇后问题python
时间: 2024-01-01 21:50:37 浏览: 46
下面是Python实现8皇后问题的回溯法代码:
```python
def is_valid(board, row, col):
# 检查列是否有冲突
for i in range(row):
if board[i] == col:
return False
# 检查右上方是否有冲突
for i, j in zip(range(row-1, -1, -1), range(col+1, len(board))):
if board[i] == j:
return False
# 检查左上方是否有冲突
for i, j in zip(range(row-1, -1, -1), range(col-1, -1, -1)):
if board[i] == j:
return False
return True
def solve(board, row):
if row == len(board):
return True
for col in range(len(board)):
if is_valid(board, row, col):
board[row] = col
if solve(board, row+1):
return True
board[row] = -1
return False
def print_board(board):
for row in board:
line = ""
for col in range(len(board)):
if row == col:
line += "Q "
else:
line += ". "
print(line)
print()
board = [-1] * 8
solve(board, 0)
print_board(board)
```
这里使用了`is_valid`函数来判断当前位置是否可用,`solve`函数实现回溯递归,`print_board`函数用于输出结果。
阅读全文