【发布时间】:2019-11-25 22:26:31
【问题描述】:
我正在编写一个 python 类来寻找 8 个皇后问题的解决方案。如何在我的 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()
我的问题是在添加女王之前缺少板的深层副本,还是只是缺少回溯?
【问题讨论】:
-
当我运行这个时,我只得到一个带有
2的网格,所有 64 个点。 -
是的,这就是我的问题——当板子在第一次尝试寻找解决方案时被填满但没有找到,所有的方格最终都会受到限制。
标签: python recursion backtracking n-queens