Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/algorithm/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Algorithm 如何有效地遍历所有边?_Algorithm_Graphics - Fatal编程技术网

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

Algorithm 如何有效地遍历所有边?,algorithm,graphics,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 a

我需要遍历图形中的所有边,并在不重复的情况下获得边的集合。
我使用了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(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”消耗时间,因为它必须在集合中检查一些时间

有没有其他方法可以让我做得更快?
提前谢谢

没有必要检查您以前是否见过边缘。由于您不会两次访问节点,因此无法两次访问同一条边(即如果图形是定向的)

如果您的图形是无向的,那么您将添加每一条边(u,v)两次(访问u时添加一次,访问v时添加一次)。若要消除此问题,可以添加一个约束,即仅在u 总之,algo应该是这样的:

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)
}
程序DFS(G,v):
发现的标签v
对于G中从v到w的所有边,相邻边(v)do
{
如果(v
将标签测试的
if
移动到
for
循环的
之外,您不应该两次穿过边(如果v被标记,返回;)。@Holt。如果我像你说的那样移动,我可能会错过一些边,因为DFS不会访问所有边。我认为下面给出的答案解决了我的问题。:)你不会错过任何东西,因为这与你的代码基本相同(我看错了,否则我不会提出这样的答案……。@Holt我不明白:)我的图是无向图。看来你推荐的约束是个好把戏。谢谢,我试试看。