如何使用广度优先搜索确定是否可以在有向图中到达顶点

时间:2017-03-27 20:03:15

标签: c++ graph-theory breadth-first-search

当试图确定有向图中的顶点是否可达时,我使用广度优先搜索来从我的源顶点到目标顶点遍历图形。然而,当我比较我在bfs期间从队列中弹出的内容(应该是我访问过的每个顶点)时,它只返回false并且从不在任何实例中为真,尽管我知道图形在某些情况下可以返回true,可以帮助一些我出去了吗?

这是我的代码

    template <typename E> 
bool Graph<E>::isReachable(E fromKey, E toKey) const
{

   Edge* tmpEdge;
   Edge* pred;
   Edge* edgeWalk; 
   Vertex* walkPtr;
   Vertex* toPtr; 
   Vertex* tmp;
   Vertex* tmpFrom;
   Vertex* tmpTo;
   queue<Vertex*> q;

   /* find source vertex */
   tmpFrom = first;
   while (tmpFrom != NULL && fromKey > tmpFrom->data)
      tmpFrom = tmpFrom->pNextVertex;
   if (tmpFrom == NULL || fromKey != tmpFrom->data)
      return false;
   /* locate destination vertex */
   tmpTo = first; 
   while (tmpTo != NULL && toKey > tmpTo->data)
      tmpTo = tmpTo->pNextVertex;
   if (tmpTo == NULL || toKey != tmpTo->data)
      return false;

  walkPtr = first;
   while (walkPtr != NULL)
   {
      walkPtr->processed = 0;
      walkPtr = walkPtr->pNextVertex;
   }
   walkPtr = first;
   while (walkPtr != NULL)
   {
      if (walkPtr->processed < 2)
      {
         if (walkPtr->processed < 1)
         {
            q.push(walkPtr); 
            walkPtr->processed = 1;
         }
      }
      while (!q.empty())
      {
          tmp = q.front();
          q.pop();
          tmp->processed = 2;
          edgeWalk = tmp->pEdge; 
          while (edgeWalk != NULL)           
          {
              toPtr = edgeWalk->destination;
              if (toPtr->processed == 0)
              {
                  toPtr->processed = 1;
                  q.push(toPtr);
              }
              edgeWalk = edgeWalk->pNextEdge;
          }
          if (tmpTo->processed = 2)
              return true;
      }
      return false;
   }
}

1 个答案:

答案 0 :(得分:0)

你的顶点列表是否正确排序?如果它不是(看起来很可能),您将无法找到from或to键并返回false。我说&#34;很可能&#34;,因为你的循环底部有几个问题,其中一个(tmpTo->processed = 2;你应该使用==)会导致函数返回true一直以来。