简体   繁体   English

如何在图形中查找所有前向和交叉边缘

[英]How to find all forward and cross edges in a graph

I know what is forward and cross edge. 我知道什么是前沿和交叉边缘。 But I am finding difficulty in implementing them in program to find all the forward and cross edges in a given graph. 但是我发现很难在程序中实现它们以在给定图中找到所有前向和交叉边缘。

Any help in this regard would be appreciated. 在这方面的任何帮助将不胜感激。

You can classify all graph edges with a DFS transversal: 您可以使用DFS横向对所有图形边缘进行分类:

DFS-Visit(u)         ▷ with edge classification. G must be a directed graph

1.        color[u] ← GRAY
2.        time ← time + 1
3.        d[u] ← time
4.        for each vertex v adjacent to u
5.            do if color[v] ← BLACK
6.                then if d[u] < d[v]
7.                            then Classify (u, v) as a forward edge
8.                            else Classify (u, v) as a cross edge
9.                        if color[v] ← GRAY
10.                            then Classify (u, v) as a back edge
11.                       if color[v] ← WHITE
12.                            then π[v] ← u
13.                                 Classify (u, v) as a tree edge
14.                                 DFS-Visit(v)
15.        color[u] ← BLACK
16.        time ← time + 1
17.        f[u] ← time

As you can see here . 正如你可以看到在这里

You can also use a clock instead of a color. 您也可以使用时钟代替颜色。 It seems easier. 看起来比较容易。 Here's the way to accomplish that: However i will post the answer in c because I do not know c++ yet, so you will have to convert it to c++. 这是达到此目的的方法:但是我会在c中发布答案,因为我还不了解c ++,因此您必须将其转换为c ++。

void DFS(Graph* G){             
int v;

for (v=0; v < G->n; v++)
  visited[v]=FALSE;

for (v=0; v < G->n; v++){
  if (!visited[v])
    Traverse(G, v);
 }

}

void Traverse(Graph* Gr, int v){                
int w;
Edge *current;

start[v]=clock;                             //We are going to classify the edges by the time they were visited
clock++;
visited[v]=TRUE;

current=Gr->stpoint[v];

while (current){
    w=current->vertex;

    if (!visited[w]) {                          
        printf("%d %d: Tree edge\n",v,w);       //If w is not visited then mark v-w as a tree edge
        if(!current)
            Traverse(Gr, w);
    }
    else{

        if((start[v] > start[w]) && (end[v] < end[w]))      //v was visited after w
            printf("%d %d: Back edge\n",v,w);
        else if ((start[v] < start[w]) && (end[v] > end[w]))    //v was visited before w
            printf("%d %d: Forward edge\n",v,w);
        else if ((start[v] > start[w]) && (end[v] > end[w]))    //
            printf("%d %d: Cross edge\n",v,w);

    }
    end[v]=clock;
    clock++;
    current=current->next;
 }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM