-1

我试图创建一个函数,返回棋盘上n皇后状态的所有相邻节点,下面是我的代码,主要是根据参数输入状态生成相邻节点列表。

#Generate neighboring state's function
def generate_neighbor_node (cur_state):
    current = cur_state
    neighbor = current
    neighbor_list = []
    for i in range(qs):
        chg_value = neighbor[i]
        chg_value +=1
        if chg_value == qs:
            chg_value =0
        neighbor[i] = chg_value 
        print neighbor       
        neighbor_list.append(neighbor)
    #Reverse the process, to change the node value back to original for next
    #loop to generate another valid neighbor state
        chg_value -=1
        if chg_value == -1:
           chg_value = (qs-1)
        neighbor[i] = chg_value    

   return neighbor_list                

print board
ai = generate_neighbor_node(board)
print ai

The output is like this:
1. [1, 3, 2, 0]
2. [2, 3, 2, 0]
3. [1, 0, 2, 0]
4. [1, 3, 3, 0]
5. [1, 3, 2, 1]
[[1, 3, 2, 0], [1, 3, 2, 0], [1, 3, 2, 0], [1, 3, 2, 0]]

但我真正想要的是包含的列表是数组 2,3,4 和 5 但不是 1 怎么办?请帮忙,谢谢。

4

1 回答 1

1

每当您打电话neighbor_list.append(neighbor)时,您只需添加对 的引用neighbor,而不是新列表。这意味着其中的每个列表neighbor_list都只是 的当前值neighbor

要解决此问题,您应该像这样复制列表:

neighbor_list.append(copy.copy(neighbor)

副本文件

于 2013-07-17T17:38:09.527 回答