使用DFS进行边缘分类

时间:2018-02-22 16:53:47

标签: python algorithm networkx graph-theory breadth-first-search

我使用networkx创建了一个图表,我想添加一个'类'在每个边缘的属性,以知道是前进,后退,交叉还是树。 作为下一步,我尝试在python中实现以下伪代码,但是当我打印图形边缘时,输出为空' class'每个边缘的属性。

DFS (V, E)

1.     for each vertex u in V[G]
2.        do color[u] ← WHITE
3.                π[u] ← NIL
4.     time ← 0
5.     for each vertex u in V[G]
6.        do if color[u] ← WHITE
7.                then DFS-Visit(u)              ▷ build a new DFS-tree from u

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

这是我的代码:

def dfs_visit(u):
    color[u] = 'gray'
    global time
    time = time + 1
    d[u] = time
    for v in G.neighbors(u):
        if color[v] == 'black':
            if d[u] < d[v]:
                G.edges[u,v]['class'] = 'forward'
            else:
                G.edges[u,v]['class'] ='cross'
            if color[v] == 'gray':
                G.edges[u, v]['class'] = 'back'
            if color[v] == 'white':
                p[v] = u
                G.edges[u, v]['class'] = 'tree'
                dfs_visit(v)
    color[u] = 'black'
    time = time + 1
    f[u] = time



for u in G.nodes():
    color[u] = 'white'
time = 0
for u in G.nodes():
    if color[u] == 'white':
        dfs_visit(u)

print(G.edges(data=True))

如果我打印所有图形边缘,我将采用以下输出:

[(1, 2, {'class': ''}), (1, 6, {'class': ''}), (2, 3, {'class': ''}), (6, 3, {'class': ''}), (3, 4, {'class': ''}), (3, 1, {'class': 'cross'}), (3, 7, {'class': ''}), (4, 5, {'class': ''}), (4, 7, {'class': ''})]

每条边的class属性都是空的。我该如何解决?

1 个答案:

答案 0 :(得分:2)

可能是缩进问题,请尝试以下方法:

def dfs_visit(u):
    color[u] = 'gray'
    global time
    time = time + 1
    d[u] = time
    for v in G.neighbors(u):
        if color[v] == 'black':
            if d[u] < d[v]:
                G.edges[u,v]['class'] = 'forward'
            else:
                G.edges[u,v]['class'] ='cross'
        if color[v] == 'gray':
            G.edges[u, v]['class'] = 'back'
        if color[v] == 'white':
            p[v] = u
            G.edges[u, v]['class'] = 'tree'
            dfs_visit(v)
    color[u] = 'black'
    time = time + 1
    f[u] = time