Python最短路径算法中list slicing代码行的作用及赋值差异解析
关于最短路径算法中
new_path = current_path[:]的疑问与解释 我正在学习Python中的最短路径算法,代码运行正常,但其中一行代码令我困惑,希望得到解释。我想理解代码中
new_path = current_path[:]这行的作用,以及将其改为new_path = current_path后结果不同的原因,完整代码如下:
# Construct the graph graph = {'0':{'.','1','2'}, '.':{'0','3'}, '1':{'0','2','4'}, '2':{'0','1','3','5'}, '3':{'.','2'}, '4':{'1','5','7'}, '5':{'2','4','6','8'}, '6':{'3','5','9'}, '7':{'4','8'}, '8':{'5','7','9'}, '9':{'6','8'}} # Function to return the shortest path between two nodes in a graph def shortest_path(graph, start_node, end_node): path_list = [[start_node]] path_index = 0 # To keep track of previously visited nodes previous_nodes = {start_node} if start_node == end_node: return path_list[0] while path_index < len(path_list): current_path = path_list[path_index] last_node = current_path[-1] next_nodes = graph[last_node] # Search for the end node within the list of next_nodes if end_node in next_nodes: current_path.append(end_node) return current_path # Add new paths for next_node in next_nodes: if not next_node in previous_nodes: new_path = current_path[:] # <-----------------------This line new_path.append(next_node) path_list.append(new_path) # To avoid backtracking previous_nodes.add(next_node) # Continue to next path in list path_index += 1 # No path is found return [] # Print the shortest path from 1 to 9 in the graph print(shortest_path(graph, '1','9'))
一、new_path = current_path[:]的作用
这行代码是对current_path做浅拷贝,生成一个和原列表内容完全相同,但内存地址独立的新列表。
在这个BFS最短路径算法里,我们需要为每个相邻节点生成一条独立的新路径——这条路径基于当前路径,再加上相邻节点。用切片拷贝后,后续对new_path的修改(比如append(next_node))只会影响这个新列表,不会改动原来的current_path,确保path_list里的每条路径都是各自独立的分支,符合BFS逐层探索路径的逻辑。
二、改为new_path = current_path结果不同的原因
Python里列表是可变对象,new_path = current_path只是让new_path指向和current_path同一个列表对象的引用,并不是创建新列表。
这时候如果执行new_path.append(next_node),会直接修改原current_path的内容,进而影响path_list中原本存储的路径。比如处理第一个相邻节点时,原路径被修改,处理下一个相邻节点时,会在已经被修改的原路径上继续添加节点,导致所有新生成的路径都共享同一个列表对象,最终完全打乱BFS的路径探索逻辑,得到错误的最短路径结果,甚至无法找到正确路径。
内容的提问来源于stack exchange,提问作者ScottC
相关产品推荐
相关产品推荐

