Write a program to Find Bridges in the graph
Example 1:
Input: n=6,edges={{1,2},{2,3},{3,1},{4,3},{5,4},{6,4},{5,6}}
Output: 3-4 is a bridge , 1
Approach:
Java
import java.util.ArrayList;public class FindBridgesInGraph {// visited array,in array,low arraystatic ArrayList<Integer> visited =new ArrayList<Integer>();static int in[];static int low[];// variable for dfs timerstatic int timer = 0;// variable for counterstatic int cnt = 0;public static void main(String[] args) {// adjacency list of the graphArrayList<ArrayList<Integer>> adj =new ArrayList<>();int v = 7;// initialization of arrayin = new int[v];low = new int[v];for (int i = 0; i < v; i++)adj.add(new ArrayList<>());
addEdge(adj, 1, 2);// call dfs to find bridgeaddEdge(adj, 2, 3);addEdge(adj, 3, 1);addEdge(adj, 4, 3);addEdge(adj, 5, 4);addEdge(adj, 6, 4);addEdge(adj, 5, 6);dfs(adj, 1, -1);}private static void dfs(ArrayList<ArrayList<Integer>> adj,int node, int parent) {visited.add(node);in[node] = timer;low[node] = timer;// increment the timer for next timetimer++;// now interate for all adjacent nodes of the// current nodesfor (int child : adj.get(node)) {// if child is same parent then continueif (child == parent)continue;// if alredy visitedif (visited.indexOf(child) != -1) {// edge node-child is a back edgelow[node] = Math.min(low[node], in[child]);} else {// edge node-child is a forward edgedfs(adj, child, node);if (low[child] > in[node]) {cnt++;System.out.println(node + " - " + child +" is a bridge " + cnt);}low[node] = Math.min(low[child], low[node]);}}}// method to add edges into graphprivate static void addEdge(ArrayList<ArrayList<Integer>> g,int u, int v) {// graph is undirectedg.get(u).add(v);g.get(v).add(u);}}
C++
#include <bits/stdc++.h>using namespace std;//adjacency list of the graphvector<int> arr[10001];//visited array,in array,low arrayint visited[10001],in[10001],low[10001];//varible for dfs timerint timer;//variable for counterint cnt;//function to add the edges into//the graphvoid addEdge(int u,int v){//graph is undirectedarr[u].push_back(v);arr[v].push_back(u);}//dfs functionvoid dfs(int node,int par){//mark the current node as visitedvisited[node]=1;//in time and low time as current timer valuein[node]=low[node]=timer;//increment the timer for next timetimer++;//now interate for all adjacent nodes of the//current nodesfor(int child:arr[node]){//if child is same parent then//continueif(child==par)continue;//if alredy visitedif(visited[child]==1){//edge node-child is a back edgelow[node]=min(low[node],in[child]);}else{//edge node-child is a forward edgedfs(child,node);if(low[child]>in[node]){cnt++;cout<<node<<" - "<<child<<" is a bridge\n";}low[node]=min(low[child],low[node]);}}}int main(){int n=6;addEdge(1,2);addEdge(2,3);addEdge(3,1);addEdge(4,3);addEdge(5,4);addEdge(6,4);addEdge(5,6);dfs(1,-1);cout<<"Number of brides are ";cout<<cnt<<"\n";return 0;}
No comments:
Post a Comment