八皇后用python写
时间: 2023-09-30 19:06:29 浏览: 118
八皇后问题源码 python
八皇后问题是一个经典的回溯算法问题,下面是用 Python 实现的代码:
```python
def printBoard(board):
for i in range(len(board)):
for j in range(len(board)):
print(board[i][j], end=' ')
print()
def isSafe(board, row, col):
for i in range(col):
if board[row][i] == 1:
return False
for i,j in zip(range(row,-1,-1), range(col,-1,-1)):
if board[i][j] == 1:
return False
for i,j in zip(range(row,len(board),1), range(col,-1,-1)):
if board[i][j] == 1:
return False
return True
def solveNQueens(board, col):
if col >= len(board):
return True
for i in range(len(board)):
if isSafe(board, i, col):
board[i][col] = 1
if solveNQueens(board, col+1):
return True
board[i][col] = 0
return False
def solve(n):
board = [[0 for x in range(n)] for y in range(n)]
if solveNQueens(board, 0) == False:
print("No solution found")
return False
printBoard(board)
return True
n = 8
solve(n)
```
该代码定义了三个函数:
- `printBoard()` 用于打印棋盘;
- `isSafe()` 判断当前位置是否可放置皇后;
- `solveNQueens()` 用于递归求解八皇后问题。
最后,调用 `solve()` 函数即可求解八皇后问题。
阅读全文