将节点标记为在出列时在BFS上访问

时间:2017-08-10 21:29:15

标签: graph-theory pseudocode breadth-first-search

关于图表上BFS遍历的一个快速而愚蠢的问题

我在许多网站上发现BFS的伪代码几乎是这样的:

BFS (Graph, root):

create empty set S
create empty queue Q      
add root to S //mark as visited here
Q.enqueue(root)                      
while Q is not empty:
    current = Q.dequeue()
    if current is the goal:
        return current
    for each node n that is adjacent to current:
        if n is not in S:
            add n to S //mark as visited here
            Q.enqueue(n)

我发现稍微更简单的是在给定节点之后将其标记为访问它而不是在执行它时,因为在后面的方法中我们需要编写一个额外的步骤。我知道这不是一件大事,但我想将一个节点标记为在一个地方而不是两个地方访问更有意义。更简洁,更容易记忆,甚至学习。

修改后的版本将如下:

BFS (Graph, root):

create empty set S
create empty queue Q      
Q.enqueue(root)                      
while Q is not empty:
    current = Q.dequeue()
    add current to s //just add this and remove the other 2 lines 
    if current is the goal:
        return current
    for each node n that is adjacent to current:
        if n is not in S:
            Q.enqueue(n)

我只是想知道这种变化是否正确,据我所知这根本不应该改变遍历的行为,是吗?

1 个答案:

答案 0 :(得分:0)

对于相邻节点,如果要更改条件,则条件应更严格:     if n is not in S and n is not in Q:

相关问题