Bridges in graph 🚩🚩🚩
Fri Jan 28 2022 17:27:26 GMT+0000 (Coordinated Universal Time)
Saved by @vaibhav_55
/* Steps:- 1)initialise two arrays in,low and vairable Time = 0; 2) first mark the node visited 3)initiliase the low[curr] & in[curr] to Time and increment time by 1 4)loop over the adjacency list of curr 5)Most important the following three condition's for child -> if Child is equal to parent of curr ---> continue -> if Child is visited(this means that this is a back edge) --> make the low of curr min of low of curr or min in child i.e low[curr] = min(low[curr],in[child]) -> if Child is not visited(this means that this is a forward edge) --> call dfs passing parent as curr node --> if,low[child] is greater than in[curr] this is bridge i.e. if(low[child]>in[curr])---->this is a bridge --> at last,while backtracking change the low of curr to min of curr or min of low of child i.e. low[curr] = min(low[curr],low[child]) The main thing here, is that we are storing for each node can it be reached from any other node ->if yes then that edge is not a bridge ->if no it is a bridge */ vector<ll> g[100001]; vector<bool> visi(100001, false); vector<ll> low(100001), in(100001); // arrrays for keeping the low and in time of node ll Time = 0; // time variable void detectBridge(ll s, ll par) { low[s] = in[s] = Time; Time++; visi[s] = true; for (ll child : g[s]) { if (child == par) // if child is equal to parent continue continue; else if (visi[child]) // if child is visited and also is not a parent { // change the low time of curr to min of low of curr or in of child low[s] = min(low[s], in[child]); } else { // if child is not visited detectBridge(child, s); // call dfs further // condition for checking the bridge if (low[child] > in[s]) // if the low[child] is more than curr this is a brigde { cout << s << "-->" << child << endl; } // while backtracking change the low of curr to min of low of curr or low of child low[s] = min(low[s], low[child]); } } }
Comments