n皇后问题中的回溯和递归(Python)

问题描述 投票:0回答:1

我正在编写一个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()

我的问题是在添加皇后之前缺少董事会的深层副本,还是只是缺乏回溯?

python recursion backtracking n-queens
1个回答
1
投票

两者都是:您在整个程序中只有一个董事会副本。您尽其所能地填充它,直到所有正方形都被占据或限制为止。搜索失败,并且您从solve返回。没有复位板的机制,程序结束。

回溯将使此过程变得简单,但需要多个中间板。而不是拥有一个单独的棋盘对象...制作一个深副本,放置女王/王后,标记适当的RESTRICTED正方形,然后将更改后的副本传递到下一个级别。如果失败返回,则该副本作为局部变量自然消失。

© www.soinside.com 2019 - 2024. All rights reserved.