我编写了一个 dfs 函数并返回所有可能的从起点到目的地点的路径。 但是,我注意到我在函数中得到了正确的路径,但我没有从函数中得到它。
res = []
Solution s:
def find all_path(graph:list(list)):
def dfs(curNode, path: list)->list[list]:
if curNode == target:
#Correct one:
#res.append(list(path))
#Wrong one:
res.append(path)
return
#all other code without modify the list of res
path = [start_point]
dfs(start_point, path)
return res
我为什么要写
res.append(list(path))
?我记得列表 A.append(list.B) 将获得 A[ [B] ] 格式。所以,应该没问题。
尝试过:搜索网站并尝试检查全局验证,但我以前一直这样做。只是这一次,我在外面没有得到正确的值。
期望:我想知道为什么。
试试这个
def find_all_paths(graph: list[list]) -> list[list]:
"""
Find all possible paths from start to destination in a graph.
Args:
graph: A list of lists representing the graph.
Returns:
A list of lists, where each sublist is a path from start to
destination.
"""
start_point, target = 0, len(graph) - 1
res = []
def dfs(cur_node: int, path: list) -> None:
"""
Depth-first search to find all paths from cur_node to destination.
Args:
cur_node: The current node.
path: The current path.
"""
if cur_node == target:
# Append a copy of the current path to the results.
res.append(list(path))
return
for neighbor in graph[cur_node]:
if neighbor not in path:
path.append(neighbor)
dfs(neighbor, path)
path.pop() # Backtrack by removing the last node from the path.
dfs(start_point, [start_point])
return res
# Example usage
graph = [[1, 2], [0, 3, 4], [0], [1, 5], [1, 6], [4], [5]]
paths = find_all_paths(graph)
print(f"All paths from 0 to 6: {paths}")
此代码将打印以下输出:
从 0 到 6 的所有路径:[[0, 1, 3, 5, 4, 6], [0, 1, 4, 6]]