Data structures 是否有一个「;官方的;,或者甚至任何正确的DFS实现?
在此示例中,提供了DFS的伪代码:Data structures 是否有一个「;官方的;,或者甚至任何正确的DFS实现?,data-structures,graph,depth-first-search,Data Structures,Graph,Depth First Search,在此示例中,提供了DFS的伪代码: DFS(source): s <- new stack visited <- {} // empty set s.push(source) while (s is not empty): current <- s.pop() if (current is in visited): continue visited.add(current) // do something with
DFS(source):
s <- new stack
visited <- {} // empty set
s.push(source)
while (s is not empty):
current <- s.pop()
if (current is in visited):
continue
visited.add(current)
// do something with current
for each node v such that (current,v) is an edge:
s.push(v)
推1
流行音乐1
将1添加到已访问的
按2,3
流行音乐2
添加2到已访问的
按1再次堆叠
当然,这不可能是正确的???您说的节点
1
将再次被推到堆栈上是正确的。但这并不重要:在下一个过程中,它基本上会被忽略,因为它已经被标记为“已访问”:
或者,如果尚未访问该节点,则只能将其添加到堆栈中:
for each node v such that (current,v) is an edge:
if (v is NOT in visited) s.push(v)
在实际实现中添加此检查并非不可能。但代码是伪代码,通常以非常通用的形式编写,为了紧凑性和通用性,这种“优化”或“改进”被忽略,只要算法正确。在这里,差异并不影响正确性:在这两种情况下,都是
// do something with current
将仅为每个节点执行一次 您说得对,节点
1
将再次被推到堆栈上。但这并不重要:在下一个过程中,它基本上会被忽略,因为它已经被标记为“已访问”:
或者,如果尚未访问该节点,则只能将其添加到堆栈中:
for each node v such that (current,v) is an edge:
if (v is NOT in visited) s.push(v)
在实际实现中添加此检查并非不可能。但代码是伪代码,通常以非常通用的形式编写,为了紧凑性和通用性,这种“优化”或“改进”被忽略,只要算法正确。在这里,差异并不影响正确性:在这两种情况下,都是
// do something with current
将仅为每个节点执行一次 @Marco13你是对的。您应该将您的评论作为答案发布。请使用正确的标签。DFS是由使用的分布式文件系统Windows@Marco13你说得对。您应该将您的评论作为答案发布。请使用正确的标签。DFS是Windows使用的分布式文件系统