【问题标题】:C/C++ Finding all paths between two vertex in unweighted & undirected graph using an adjacency matrixC/C++ 使用邻接矩阵在未加权和无向图中查找两个顶点之间的所有路径
【发布时间】:2018-04-03 04:21:13
【问题描述】:

我正在尝试使用邻接矩阵查找起始顶点和结束顶点之间的所有路径。我的图表是未加权且无向的。

我试图遵循这个算法,但是我在每个部分都卡住了。

算法:

procedure FindAllPaths(u, dest)
{
   push u to stack;
   if(u == dest)
   {
      print stack;
   }
   else
   {
      foreach v that is adjacent with u and not in stack now
      {
         FindAllPaths(v, dest);
      }
   }
   pop from stack;
}

我的代码:

void AdjacencyMatrix :: Find_All_Paths(int Origin, int Destination)
{
      /*
      MATRIX:
      0 1 0 1 1
      0 1 0 1 1
      0 0 0 1 0
      0 1 1 1 0
      1 1 0 1 1
      */
    //Push Origin to stack
    Push_Vertex.push(Origin);

    //Determine if Origin == Destination, if so, print the stack
    if(Origin == Destination)
    {
        while(!Push_Vertex.empty())
        {
            cout << Push_Vertex.top() << " ";
            Push_Vertex.pop();
        }//while
        cout << endl;
    }//if

    else

}//Find_All_Paths()

【问题讨论】:

  • 这使用了DFS,但是你没有在循环内调用FindAllPaths。如果您只使用int,您究竟如何检查节点是否相邻。
  • @codekaizer DFS 实际上。
  • @FeiXiang,哦,对了。被adjacent这个词蒙蔽了双眼
  • 我忘了添加检查以查看顶点是否已经在堆栈上,请参阅我编辑的答案。

标签: c++ graph-theory adjacency-matrix


【解决方案1】:

您需要遍历当前节点对应的行以找到与其相邻的节点。这在一定程度上取决于您的邻接矩阵是如何实现的,但它看起来像这样:

for(int v = 0; v < n; v++)
{
    if(adj[Origin][v] && !inStack[v])
    {
        Find_All_Paths(Origin, Destination);
    }
}

adj 是您的邻接矩阵,如果从u 到v 存在边,则adj[u][v] 为真。 inStack 是一个布尔数组,用于存储顶点是否在堆栈中,以便快速检查。将数组初始化为false,将顶点对应的索引设置为插入栈时为true,弹出时为false。

完整代码:

void AdjacencyMatrix :: Find_All_Paths(int Origin, int Destination)
{
    //Push Origin to stack
    Push_Vertex.push(Origin);
    inStack[Origin] = true;

    //Determine if Origin == Destination, if so, print the stack
    if(Origin == Destination)
    {
        while(!Push_Vertex.empty())
        {
            cout << Push_Vertex.top() << " ";
            Push_Vertex.pop();
        }//while
        cout << endl;
    }//if

    else
    {
        for(int v = 0; v < n; v++)
        {
            if(adj[Origin][v] && !inStack[v])
            {
                Find_All_Paths(Origin, Destination);
            }
        }
    }
    Push_vertex.pop();
    inStack[Origin] = false;

}//Find_All_Paths()

【讨论】:

    猜你喜欢
    • 2012-12-18
    • 1970-01-01
    • 1970-01-01
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-03
    • 2017-07-03
    相关资源
    最近更新 更多