Python/graphs/finding_bridges.py

43 lines
976 B
Python
Raw Normal View History

2018-10-19 12:48:28 +00:00
# Finding Bridges in Undirected Graph
def computeBridges(graph):
2018-10-19 12:48:28 +00:00
id = 0
n = len(graph) # No of vertices in graph
2018-10-19 12:48:28 +00:00
low = [0] * n
visited = [False] * n
def dfs(at, parent, bridges, id):
visited[at] = True
low[at] = id
id += 1
for to in graph[at]:
2018-10-19 12:48:28 +00:00
if to == parent:
pass
elif not visited[to]:
dfs(to, at, bridges, id)
low[at] = min(low[at], low[to])
if at < low[to]:
bridges.append([at, to])
else:
# This edge is a back edge and cannot be a bridge
low[at] = min(low[at], to)
bridges = []
for i in range(n):
2019-10-05 05:14:13 +00:00
if not visited[i]:
2018-10-19 12:48:28 +00:00
dfs(i, -1, bridges, id)
print(bridges)
2019-10-05 05:14:13 +00:00
graph = {
2019-10-05 05:14:13 +00:00
0: [1, 2],
1: [0, 2],
2: [0, 1, 3, 5],
3: [2, 4],
4: [3],
5: [2, 6, 8],
6: [5, 7],
7: [6, 8],
8: [5, 7],
}
computeBridges(graph)