n皇后问题最简单回溯写法

class NQueen:
    def __init__(self, n):
        self.n = n
        self.cnt = 0
        self.column = [0 for i in range(n + 1)]  # column[i] means the column of queen in the i row

    def can_place(self, index: int):  # 检查column[index]是否满足规则
        for i in range(1, index):  # 对比之前的每行
            if self.column[i] == self.column[index] or abs(self.column[index] - self.column[i]) == (index - i):
                return False
        return True

    def print_chessboard(self):
        print(self.cnt)
        for i in range(1, n + 1):
            for j in range(1, n + 1):
                if self.column[i] == j:
                    print("\033[92mQ\033[0m", end=" ")
                else:
                    print("□", end=" ")
            print()
        print()

    def n_queen(self, index):
        if index == self.n + 1:
            # print(column[1:])
            self.cnt += 1
            self.print_chessboard()
            return
        for i in range(1, self.n + 1):
            self.column[index] = i
            if self.can_place(index):
                self.n_queen(index + 1)
            # 如果不能放置,则回溯,即放到下一列


n = 8
nQueen = NQueen(n)
nQueen.n_queen(1)
posted @ 2025-07-11 10:25  无眠之月  阅读(17)  评论(0)    收藏  举报