如何有效地遍历所有边缘?

时间:2016-04-18 07:37:17

标签: algorithm graphics

我需要遍历图中的所有边并获得边的集合而不重复 我使用DFS并继续向集合添加边缘,如下所示。

   procedure DFS(G,v):
   label v as discovered
   for all edges from v to w in G.adjacentEdges(v) do
   {
           addEdge(v,w);              //get edges 
           if vertex w is not labeled as discovered then
              recursively call DFS(G,w)
   }

但由于它不应该重复边缘,我需要做一些检查 ' addEdges'

  addEdges(v,w)
  {
    if either  v or w is not in HashTble(nodes) /
       {
         add edge(v,w) to collection(edges)
         add v and w to HashTble(nodes)
       } 
    else
       {  //both v and w in HashTble(nodes)
          if edge(v,w) is not in collection(edges)
             add edge(v,w) to collection(edges)
       }
  }

这就是我做到的。问题是图表可能非常大,而且在这样的图形中,addEdges'消耗时间,因为它必须有时检查集合。

还有其他方法可以更快地完成这项工作吗? 提前谢谢!

1 个答案:

答案 0 :(得分:3)

没有必要检查你之前是否看过边缘。由于您没有两次访问节点,因此您将无法两次使用相同的边缘(即图形是否已定向)。

如果您的图表是无向的,那么您将添加每个边缘(u,v)两次(一次访问u时再次,当您访问v时)。要摆脱这种情况,你可以添加你只添加边缘的约束,如果你<诉

总而言之算法应该是这样的:

procedure DFS(G,v):
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
{
       add edge(v,w) to output edges   
       if vertex w is not labeled as discovered then
          recursively call DFS(G,w)
}

或者,如果您有无向图:

procedure DFS(G,v):
label v as discovered
for all edges from v to w in G.adjacentEdges(v) do
{
       if (v < w) add edge(v,w) to output edges
       if vertex w is not labeled as discovered then
          recursively call DFS(G,w)
}