Algorithm 小型高炉详细说明
标准bfs实现类似(由维基百科提供): 我想知道为什么在检查电流是否为目标时,不能通过电流相邻的邻居进行检查。例如,例如:Algorithm 小型高炉详细说明,algorithm,optimization,breadth-first-search,Algorithm,Optimization,Breadth First Search,标准bfs实现类似(由维基百科提供): 我想知道为什么在检查电流是否为目标时,不能通过电流相邻的邻居进行检查。例如,例如: Breadth-First-Search(Graph, root): create empty set S create empty queue Q root.parent = NIL if root is the goal return root Q.enqueue(root)
Breadth-First-Search(Graph, root):
create empty set S
create empty queue Q
root.parent = NIL
if root is the goal
return root
Q.enqueue(root)
while Q is not empty:
current = Q.dequeue()
for each node n that is adjacent to current:
if n is the goal // check here instead
n.parent = current
return n
if n is not in S:
add n to S
n.parent = current
Q.enqueue(n)
这个想法是,当你在邻居身上发现这个词时,你会立刻抓住它。您可以确保这是最短的路径,因为队列中的路径不可能已经包含路径,因为在发生这种情况之前,我们也会发现这种情况
我知道这需要在while循环之前添加一个额外的检查,以查看root是否是目标,但除此之外,bfs不这样实现有什么原因吗?从技术上讲,它应该更快,对吗?如果您检查根目录,那么您的版本可以正常工作(您应该把它放在问题中) 在某些情况下,您的方式会更快,在某些情况下,您的方式会更慢。例如,如果访问每个节点的内容两次会受到某种惩罚(如额外的缓存未命中),则速度可能会较慢
通常差别不大,人们只是因为代码更简单就用第一种方法来实现。我想我应该进一步重构它。我注意到root并没有直接添加到S,这意味着它将在稍后添加,然后再次检查。我将S和Q的创建移动到早期根返回之后。切换了while,这意味着root不必排队到Q,然后检查Q以查看root是否在其中,然后将root出列。我将in S检查移动到for each循环的第一个内部,因为该检查将阻止目标检查一次或多次,目标检查将只阻止in S检查一次。它还允许我删除n.parent=当前代码行重复,这无助于提高性能,但我不喜欢重复
Breadth-First-Search(Graph, root):
root.parent = NIL
if root is the goal
return root
create empty set S
add root to S
create empty queue Q
current = root
while true
for each node n that is adjacent to current:
if n in S:
continue
n.parent = current
if n is the goal
return n
add n to S
Q.enqueue(n)
if Q empty
break
current = Q.dequeue()
Breadth-First-Search(Graph, root):
root.parent = NIL
if root is the goal
return root
create empty set S
add root to S
create empty queue Q
current = root
while true
for each node n that is adjacent to current:
if n in S:
continue
n.parent = current
if n is the goal
return n
add n to S
Q.enqueue(n)
if Q empty
break
current = Q.dequeue()