我正在编写一个python类来寻找8个queens问题的解决方案。如何在我的solve方法中正确地实现回溯?我认为递归应该可以工作,但是,程序在第一次尝试时没有找到解决方案后停止,并且不会发生回溯。所有帮助器方法都能正常工作。
EMPTY = 0
QUEEN = 1
RESTRICTED = 2
class Board:
# initializes a 8x8 array
def __init__ (self):
self.board = [[EMPTY for x in range(8)] for y in range(8)]
# pretty prints board
def printBoard(self):
for row in self.board:
print(row)
# places a queen on a board
def placeQueen(self, x, y):
# restricts row
self.board[y] = [RESTRICTED for i in range(8)]
# restricts column
for row in self.board:
row[x] = RESTRICTED
# places queen
self.board[y][x] = QUEEN
self.fillDiagonal(x, y, 0, 0, -1, -1) # restricts top left diagonal
self.fillDiagonal(x, y, 7, 0, 1, -1) # restructs top right diagonal
self.fillDiagonal(x, y, 0, 7, -1, 1) # restricts bottom left diagonal
self.fillDiagonal(x, y, 7, 7, 1, 1) # restricts bottom right diagonal
# restricts a diagonal in a specified direction
def fillDiagonal(self, x, y, xlim, ylim, xadd, yadd):
if x != xlim and y != ylim:
self.board[y + yadd][x + xadd] = RESTRICTED
self.fillDiagonal(x + xadd, y + yadd, xlim, ylim, xadd, yadd)
# recursively places queens such that no queen shares a row or
# column with another queen, or in other words, no queen sits on a
# restricted square. Should solve by backtracking until solution is found.
def solve(self, queens):
if queens == 8:
return True
for i in range(8):
if self.board[i][queens] == EMPTY:
self.placeQueen(queens, i)
if self.solve(queens - 1):
return True
self.board[i][queens] = RESTRICTED
return False
b1 = Board()
b1.solve(7)
b1.printBoard()我的问题是在添加皇后之前缺乏一个深入的董事会副本,还是只是缺乏回溯?
发布于 2019-11-26 06:46:35
两者兼而有之:在你的整个程序中,你只有一个板子的副本。您可以尽可能地填充它,直到所有的方块都被占用或限制;搜索失败,然后您从solve返回。没有重置电路板的机制,你的程序就结束了。
回溯将使这一切变得简单,代价是多个中间板。而不是只有一个棋盘对象。制作一个很深的副本,放置皇后,标记适当的限制方块,并将修改后的副本传递到下一关卡。如果返回失败,则让副本作为局部变量自然消失。
https://stackoverflow.com/questions/59041018
复制相似问题