我遇到了BFS在python中解决8个难题的问题。我需要移动方法来返回一个新的拼图而不是修改原始拼图。下面的输出显示正在修改原始拼图而不是正在制作的新拼图。我试过复制但是没有用,而且列表没有深层复制。是否有一种简单的方法可以从原始对象制作新对象?
def move(puzzle, direction):
# find where the zero (gap) is and swap in the given direction
row_count = 0
for row in puzzle:
if '0' in row:
gapx = row.index('0')
gapy = row_count
row_count = row_count + 1
# move it accordingly, as long as the move is legal
if direction == 'up' and (gapy==1 or gapy==2):
temp = puzzle[gapy-1][gapx]
puzzle[gapy-1][gapx] = '0'
puzzle[gapy][gapx] = temp
return puzzle
pretty_print(puzzle_state)
new_puzzle = move(puzzle_state, 'up')
pretty_print(puzzle_state)
输出:
123
804
765
103
824
765
答案 0 :(得分:0)
copy.deepcopy()工作,我最初尝试使用puzzle.deepcopy(),这不是使用深层复制的正确方法。谢谢!