如何实现广度优先搜索遍历?遍历、广度、如何实现

2023-09-11 07:10:22 作者:淡薄如素

我不能清楚地了解如何使用队列来实现广度优先搜索。

I can't clearly understand how to implement breadth first search using a queue.

这就是我理解的:

 create queue Q
 enqueue root onto Q

while( !Q.empty() )
{
  node t = Q.deque();
  if(t is the goal we're seeking)
      return t;
  enqueue   t->leftchild
  enqueue   t->rightchild
}

让我错过了这里?

so what am i missing out here?

推荐答案

正如评论所说,你错误地认为,每个国家都有,可以从它能够生成2个状态。

As stated in the comments, you wrongly assume that each state has exactly 2 states that can be generated from it.

正确的算法是:

BFS(G,v):
      create a queue Q
      enqueue v onto Q
      mark v
      while Q is not empty:
          t ← Q.dequeue()
          if t is what we are looking for:
              return t
          for all edges (t,u) in G do
             if u is not marked:
                  mark u
                  enqueue u onto Q 

抵免维基百科