【发布时间】:2017-02-04 14:57:27
【问题描述】:
标准的 bfs 实现类似于(由 Wikipedia 提供):
Breadth-First-Search(Graph, root):
create empty set S
create empty queue Q
root.parent = NIL
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
n.parent = current
Q.enqueue(n)
我想知道为什么在查看与当前相邻的邻居时无法检查当前是否是目标。例如。类似:
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 没有像这样实现?从技术上讲,它应该更快吧?
【问题讨论】:
标签: algorithm optimization breadth-first-search