将每个独特的解决方案附加到皇后拼图的列表。我不知道为什么最后一个解决方案是附加到列表中的唯一解决方案?



我试图将每个单独的解决方案保存到n-Queens难题中。但是,当我尝试将每个列表添加为子列表时,与10个单独的解决方案相反,仅将最后一个解决方案添加到列表(10次)。我的目标是确保每次运行董事会仅在尚未找到的新解决方案时都被打印并添加到列表中。

def share_diagonal(x0, y0, x1, y1):
    """ Is (x0, y) on the same shared diagonal with (x1, y1)? """
    dx = abs(x1 - x0)  # Calc the absolute y distance
    dy = abs(y1 - y0)  # Calc the absolute x distance
    return dx == dy  # They clash if dx == yx

def col_clashes(bs, c):
    """ Return True if the queen at column c clashes
        with any queen to its left.
    """
    for i in range(c):  # Look at all columns to the left of c
        if share_diagonal(i, bs[i], c, bs[c]):
            return True
    return False  # No clashes - col c has a safe placement

def has_clashes(the_board):
    """ Determine whether we have any queens clashing on the diagonal.
        We're assuming here that the_board is a permutation of column
        numbers, so we're not explicitly checking row or column clashes.
    """
    for col in range(1, len(the_board)):
        if col_clashes(the_board, col):
            return True
    return False
solutions = []
def main(board_size):
    import random
    global solutions
    rng = random.Random()  # Instantiate a generator
    bd = list(range(board_size))  # Generate the initial permutation
    num_found = 0
    tries = 0
    while num_found < 10:
        rng.shuffle(bd)
        tries += 1
        if not has_clashes(bd):
            print("Found solution {0} in {1} tries.".format(bd, tries))
            solutions.append(bd)  # This is the section in which I am trying to save each individual solution into a list. 
            tries = 0
            num_found += 1

main(8)
for i in solutions:
    print(i)  # When I print off the list, all items in the list are replica's of the last solution found. Not each individual solution. I don't know why this is occurring.

只是更改

solutions.append(bd)

to

solutions.append(list(bd))

创建您当前解决方案的副本。列表中10次使用相同解决方案的问题是因为您在结果列表中添加了bd的引用,但随后将bd列出。

为了跳过重复解决方案

if not has_clashes(bd):

to

if not has_clashes(bd) and bd not in solutions:

相关内容

最新更新