forked from anishpatil31/CP-Templates-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBridges.cpp
50 lines (41 loc) · 901 Bytes
/
Bridges.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
// Code for finding bridges in a graph.
// Time Complexity - O(n + m) where n is the number of vertices and m is the number of edges in the graph.
vi adj[LIM];
bool visited[LIM];
int tin[LIM], low[LIM], timer;
set<pii> bridges;
void dfs(int u, int p)
{
visited[u] = true;
tin[u] = low[u] = timer++;
for(auto x : adj[u])
{
if(x == p)
continue;
if(visited[x])
low[u] = min(low[u], tin[x]);
else
{
dfs(x, u);
low[u] = min(low[u], low[x]);
if(low[x] > tin[u])
bridges.insert({u, x});
}
}
}
void findBridges()
{
for(int i=0; i<LIM; i++)
{
visited[i] = false;
adj[i].clear();
tin[i] = low[i] = -1;
}
timer = 0;
bridges.clear();
for(int i=1; i<=n; i++)
{
if(!visited[i])
dfs(i, -1);
}
}