【发布时间】:2023-03-19 18:10:02
【问题描述】:
我正在尝试实现 DFS 算法来确定 start 节点和 target 节点之间是否存在路径。这是我到目前为止的代码:
# Depth-first search
def find_path2(s, t):
s.visited = True
if s.data == t.data:
return True
for node in s.neighbors:
if not node.visited:
return find_path2(graph, node, t)
node_0 = Node(0)
node_1 = Node(1)
node_2 = Node(2)
node_3 = Node(3)
node_4 = Node(4)
node_5 = Node(5)
node_6 = Node(6)
node_0.neighbors = [node_1]
node_1.neighbors = [node_2]
node_2.neighbors = [node_3, node_0]
node_3.neighbors = [node_2]
node_4.neighbros = [node_6]
node_5.neighbros = [node_4]
node_6.neighbors = [node_5]
start = node_2
target = node_0
if find_path2(start, target):
print("There is a path between {} and {}".format(start.data, target.data))
else:
print("There is no path between {} and {}".format(start.data, target.data))
node_2 有 node_3 和 node_0 作为邻居,所以它应该打印它们之间有一条路径。我知道 return 语句在第一次执行期间退出了 for 循环,因为 return 语句退出了函数,因此从不访问 node_0。
我的问题是,最优雅的方法是什么?谢谢!
【问题讨论】:
-
这段代码是否按预期工作?维基百科上的 DFS 伪代码很简单,IMO。我认为
find_path2(my_graph, node, t)处的代码错误,因为my_graph不存在并且只有2 个参数要传递 -
代码中有很多错误,但您描述的问题可能会发生,因为您只考虑
find_path2中的一个邻居。您可以尝试将for循环替换为return any(find_path2(node, t) for node in s.neighbors if not node.visited)。 -
my_graph是一个旧参数,我忘记了,但在测试时我已将其删除。
标签: python for-loop recursion return depth-first-search