def number_of_descendants(S, root): nd = {} for node in S: nd[node] = 0 ancestors = create_ancestors(S, root) for node in nd: for a in ancestors: if node in ancestors[a]: nd[node] += 1 return nd
def bridge_edges(G, root): S = create_rooted_spanning_tree(G, root) po = post_order(S, root) ancestors = create_ancestors(S, root) nd = number_of_descendants(S, root) l, h = po_low_high(S, root, po) bridges = [] for node in S: for n in S[node]: if n not in ancestors[node]: if S[node][n] == 'green': if h[n] <= po[n]: if l[n] > abs(nd[n] - po[n]): bridges.append((node, n)) return bridges
def bridge_edges(G, root): S = create_rooted_spanning_tree(G, root) po = post_order(S, root) ancestors = create_ancestors(S, root) nd = number_of_descendants(S, root) l, h = po_low_high(S, root, po) bridges = [] for node in S: for n in S[node]: if n not in ancestors[node]: if S[node][n] == 'green': if h[n] <= po[n]: if l[n] > abs(nd[n]-po[n]): bridges.append((node, n)) return bridges
def po_low_high(S, root, po): lpo, hpo = {}, {} ancestors = create_ancestors(S, root) reverse_po = dict(zip(po.values(), po)) for i in range(1, len(reverse_po) + 1): n = reverse_po[i] temp = [po[n]] for node in S[n]: if node not in ancestors[n]: temp.append(po[node]) for x in S[node]: if S[node][x] == 'red': temp.append(po[x]) lpo[n], hpo[n] = min(temp), max(temp) return lpo, hpo
def po_low_high(S, root, po): lpo, hpo = {}, {} ancestors = create_ancestors(S, root) reverse_po = dict(zip(po.values(),po)) for i in range(1, len(reverse_po)+1): n = reverse_po[i] temp = [po[n]] for node in S[n]: if node not in ancestors[n]: temp.append(po[node]) for x in S[node]: if S[node][x] == 'red': temp.append(po[x]) lpo[n], hpo[n] = min(temp), max(temp) return lpo, hpo