Bridges in a connected graph

后端 未结 3 634
长发绾君心
长发绾君心 2020-12-04 15:56

I have a programming task(not homework.) where I have to find the bridges in a graph. I worked on it a bit myself, but could not come up with anything satisfactory. So i goo

3条回答
  •  自闭症患者
    2020-12-04 16:37

    Not a new answer, but I needed this in Python. Here's a translation of the algorithm for an undirected NetworkX Graph object G:

    def bridge_dfs(G,u,v,cnt,low,pre,bridges):
        cnt    += 1
        pre[v]  = cnt
        low[v]  = pre[v]
    
        for w in nx.neighbors(G,v):
            if (pre[w] == -1):
                bridge_dfs(G,v,w,cnt,low,pre,bridges)
    
                low[v] = min(low[v], low[w])
                if (low[w] == pre[w]):
                    bridges.append((v,w))
    
            elif (w != u):
                low[v] = min(low[v], pre[w])
    
    def get_bridges(G):
        bridges = []
        cnt     = 0
        low     = {n:-1 for n in G.nodes()}
        pre     = low.copy()
    
        for n in G.nodes():
             bridge_dfs(G, n, n, cnt, low, pre, bridges)
    
        return bridges # <- List of (node-node) tuples for all bridges in G
    

    Be careful of Python's recursion depth limiter for large graphs...

提交回复
热议问题