python实现4*4的N皇后问题
时间: 2023-06-04 16:03:37 浏览: 92
python 实现N皇后
可以使用回溯算法来解决4*4的N皇后问题,以下是Python代码:
def is_valid(board, row, col):
"""
检查当前位置是否合法
"""
for i in range(row):
if board[i] == col or abs(board[i] - col) == row - i:
return False
return True
def solve_n_queens(board, row, res):
"""
解决N皇后问题
"""
if row == len(board):
res.append(["".join(["Q" if c == i else "." for c in board]) for i in range(len(board))])
return
for col in range(len(board)):
if is_valid(board, row, col):
board[row] = col
solve_n_queens(board, row + 1, res)
board[row] = -1
def solve_n_queens_main(n):
"""
N皇后问题入口函数
"""
board = [-1] * n
res = []
solve_n_queens(board, 0, res)
return res
# 测试代码
res = solve_n_queens_main(4)
for i in res:
for j in i:
print(j)
print()
阅读全文