我为N皇后问题编写了Python代码,它会在找到每个解时将其打印出来。
如何修改这段代码,以返回所有解(棋盘配置)的列表,而不是打印它们?
我尝试了以下方式:
然而,只要找到第一个解决方案,它就会返回,因此“solutions”列表只包含一个可能的棋盘配置。
我该如何使其构建整个列表?
def solve(n):
#prepare a board
board = [[0 for x in range(n)] for x in range(n)]
#set initial positions
place_queen(board, 0, 0)
def place_queen(board, row, column):
"""place a queen that satisfies all the conditions"""
#base case
if row > len(board)-1:
print board
#check every column of the current row if its safe to place a queen
while column < len(board):
if is_safe(board, row, column):
#place a queen
board[row][column] = 1
#place the next queen with an updated board
return place_queen(board, row+1, 0)
else:
column += 1
#there is no column that satisfies the conditions. Backtrack
for c in range(len(board)):
if board[row-1][c] == 1:
#remove this queen
board[row-1][c] = 0
#go back to the previous row and start from the last unchecked column
return place_queen(board, row-1, c+1)
def is_safe(board, row, column):
""" if no other queens threaten a queen at (row, queen) return True """
queens = []
for r in range(len(board)):
for c in range(len(board)):
if board[r][c] == 1:
queen = (r,c)
queens.append(queen)
for queen in queens:
qr, qc = queen
#check if the pos is in the same column or row
if row == qr or column == qc:
return False
#check diagonals
if (row + column) == (qr+qc) or (column-row) == (qc-qr):
return False
return True
solve(4)
如何修改这段代码,以返回所有解(棋盘配置)的列表,而不是打印它们?
我尝试了以下方式:
def solve(n):
#prepare a board
board = [[0 for x in range(n)] for x in range(n)]
#set initial positions
solutions = []
place_queen(board, 0, 0, solutions)
def place_queen(board, row, column, solutions):
"""place a queen that satisfies all the conditions"""
#base case
if row > len(board)-1:
solutions.append(board)
return solutions
#check every column of the current row if its safe to place a queen
while column < len(board):
if is_safe(board, row, column):
#place a queen
board[row][column] = 1
#place the next queen with an updated board
return place_queen(board, row+1, 0, solutions)
else:
column += 1
#there is no column that satisfies the conditions. Backtrack
for c in range(len(board)):
if board[row-1][c] == 1:
#remove this queen
board[row-1][c] = 0
#go back to the previous row and start from the last unchecked column
return place_queen(board, row-1, c+1, solutions)
然而,只要找到第一个解决方案,它就会返回,因此“solutions”列表只包含一个可能的棋盘配置。
我该如何使其构建整个列表?
print
和return
的区别:https://dev59.com/sWsz5IYBdhLWcg3wxq4V (请不要在一个帖子中问多个问题,特别是当其中一个是重复的)。 - jonrsharpeprint
和return
之间的区别非常明显。让我困扰的是,当我可以逐个轻松打印预期结果时,我很难想出如何返回一组预期结果。 - Maximus S