From b92284175ec3a6f1ba5f2130c3098633eacf96a2 Mon Sep 17 00:00:00 2001 From: SankalpGupta Date: Thu, 1 Oct 2020 14:42:56 +0530 Subject: [PATCH] added bridges-detection algo in graphs --- Graph Algorithms/Bridges-in-graph.cpp | 76 +++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 Graph Algorithms/Bridges-in-graph.cpp diff --git a/Graph Algorithms/Bridges-in-graph.cpp b/Graph Algorithms/Bridges-in-graph.cpp new file mode 100644 index 0000000..8e825e8 --- /dev/null +++ b/Graph Algorithms/Bridges-in-graph.cpp @@ -0,0 +1,76 @@ +// Algorithm to find the bridges in graph +// A bridge is an edge in graph which after removing distribute the graph in connected components + +#include +#define ll long long int +#define vi vector +#define vll vector +#define vvi vector +#define vvl vector +#define pb push_back +#define mp make_pair +#define pii pair +#define pll pair +#define vpii vector +#define vpll vector +#define ff first +#define ss second +#define fastio ios_base::sync_with_stdio(false) , cin.tie(NULL) ,cout.tie(NULL) + +using namespace std; + +vi g[100001];// adjacency list +vector vis; +vi tin,low; +int timer; + +void dfs(int v,int p=-1){ + vis[v]=true; + tin[v]=low[v]=timer++; + for(int x:g[v]){ + if(x==p) continue; + if(vis[x]){ + low[v]=min(low[v],tin[x]); + } + else + { + dfs(x,v); + low[v]=min(low[v],low[x]); + if(low[x]>tin[v]) + { + bridge_found(x,v); + } + } + } +} + +void find_bridges(int n){ + timer=0; + tin.assign(n+1,-1); + low.assign(n+1,-1); + vis.assign(n+1,false); + for(int i=1;i<=n;i++){ + if(!vis[i]) + dfs(i); + } +} + +void bridge_found(int a,int b){ + cout<<" The Bridge is found between "<>n>>q; + while(q--){ + int u,v; + cin>>u>>v; + g[u].pb(v); + g[v].pb(u); + } + + find_bridges(n); + return 0; +} \ No newline at end of file