MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / compute_bridges

Function compute_bridges

graphs/finding_bridges.py:60–100  ·  view source on GitHub ↗

Return the list of undirected graph bridges [(a1, b1), ..., (ak, bk)]; ai <= bi >>> compute_bridges(__get_demo_graph(0)) [(3, 4), (2, 3), (2, 5)] >>> compute_bridges(__get_demo_graph(1)) [(6, 7), (0, 6), (1, 9), (3, 4), (2, 4), (2, 5)] >>> compute_bridges(__get_demo_graph(2)

(graph: dict[int, list[int]])

Source from the content-addressed store, hash-verified

58
59
60def compute_bridges(graph: dict[int, list[int]]) -> list[tuple[int, int]]:
61 """
62 Return the list of undirected graph bridges [(a1, b1), ..., (ak, bk)]; ai <= bi
63 >>> compute_bridges(__get_demo_graph(0))
64 [(3, 4), (2, 3), (2, 5)]
65 >>> compute_bridges(__get_demo_graph(1))
66 [(6, 7), (0, 6), (1, 9), (3, 4), (2, 4), (2, 5)]
67 >>> compute_bridges(__get_demo_graph(2))
68 [(1, 6), (4, 6), (0, 4)]
69 >>> compute_bridges(__get_demo_graph(3))
70 []
71 >>> compute_bridges({})
72 []
73 """
74
75 id_ = 0
76 n = len(graph) # No of vertices in graph
77 low = [0] * n
78 visited = [False] * n
79
80 def dfs(at, parent, bridges, id_):
81 visited[at] = True
82 low[at] = id_
83 id_ += 1
84 for to in graph[at]:
85 if to == parent:
86 pass
87 elif not visited[to]:
88 dfs(to, at, bridges, id_)
89 low[at] = min(low[at], low[to])
90 if id_ <= low[to]:
91 bridges.append((at, to) if at < to else (to, at))
92 else:
93 # This edge is a back edge and cannot be a bridge
94 low[at] = min(low[at], low[to])
95
96 bridges: list[tuple[int, int]] = []
97 for i in range(n):
98 if not visited[i]:
99 dfs(i, -1, bridges, id_)
100 return bridges
101
102
103if __name__ == "__main__":

Callers

nothing calls this directly

Calls 1

dfsFunction · 0.70

Tested by

no test coverage detected