只是一个快速的和愚蠢的问题时,对BFS访问,关于图作为出队
我在很多网站上发现的伪代码为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)
我刚刚发现稍微简单deqeuing之后的访问标志着一个给定的节点,而不是enqeuing一个的时候,因为在以后的方法,我们将需要编写一个额外的步骤。我知道这是不是一个大的事情,但我想这更有意义的一个地方作为走访的而不是两个标记一个节点。更简洁,更易于记忆,甚至学习。
修改后的版本将是就像这样:
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)
我只是想知道,如果这个改变是正确的,因为据我所知,这不应该改变遍历的行为在所有的,不它?