Skip to content

Commit bb36688

Browse files
authored
Merge pull request #881 from Karnika06/Devincept15
Added Bridge edge in Graph problem
2 parents 6443a09 + cde16e8 commit bb36688

File tree

2 files changed

+123
-76
lines changed

2 files changed

+123
-76
lines changed

Codechef Problems/MaximumArrayXOR.java

Lines changed: 0 additions & 76 deletions
This file was deleted.
Lines changed: 123 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,123 @@
1+
/*
2+
Implementation of Bridge edge in Graph problem
3+
4+
Problem statement:
5+
Given an undirected graph of V vertices and E edges and another edge (c-d), the task is to
6+
find if the given edge is a bridge in graph, i.e., removing the edge disconnects the graph.
7+
8+
Link to the problem: https://practice.geeksforgeeks.org/problems/bridge-edge-in-graph/1
9+
10+
*/
11+
12+
#include<bits/stdc++.h>
13+
using namespace std;
14+
15+
16+
class Solution
17+
{
18+
public:
19+
20+
void dfs( vector<int> adj[],vector<int>&v,int i)
21+
{
22+
//marking visited
23+
v[i]=1;
24+
25+
//traversing adjacent node
26+
for(auto x:adj[i])
27+
{
28+
if(!v[x])
29+
dfs(adj,v,x);
30+
31+
}
32+
33+
}
34+
35+
bool connected(vector<int>adj[],int n,int c,int d)
36+
{
37+
vector<int>v(n,0);
38+
39+
// dfs from edge c
40+
dfs(adj,v,c);
41+
42+
//if edge d is not visited means not connected
43+
if(v[d]==0)
44+
return false;
45+
46+
return true;
47+
48+
}
49+
50+
//Function to find if the given edge is a bridge in graph.
51+
int isBridge(int n, vector<int>adj[], int c, int d)
52+
{
53+
//if graph is not connected
54+
if(!connected(adj,n,c,d))
55+
return 0;
56+
57+
else
58+
{
59+
//removing edge c and d
60+
adj[c].erase(remove(adj[c].begin(), adj[c].end(), d), adj[c].end());
61+
adj[d].erase(remove(adj[d].begin(), adj[d].end(), c), adj[d].end());
62+
63+
//if connected means no bridge
64+
if(connected(adj,n,c,d))
65+
return 0;
66+
else
67+
return 1;
68+
}
69+
70+
}
71+
};
72+
73+
// Driver Code Starts
74+
int main()
75+
{
76+
int t;
77+
cin >> t;
78+
while (t--)
79+
{
80+
int V, E;
81+
cin >> V >> E;
82+
vector<int> adj[V];
83+
int i=0;
84+
while (i++<E)
85+
{
86+
int u, v;
87+
cin >> u >> v;
88+
adj[u].push_back (v);
89+
adj[v].push_back (u);
90+
}
91+
92+
int c,d;
93+
cin>>c>>d;
94+
95+
Solution obj;
96+
cout << obj.isBridge(V, adj, c, d) << "\n";
97+
}
98+
99+
return 0;
100+
}
101+
102+
103+
/*
104+
Time Complexity : O(V+E)
105+
Space Complexity : O(V)
106+
107+
Input:
108+
t=1
109+
V=4 E=3
110+
0 1
111+
1 2
112+
2 3
113+
c=1 d=2
114+
115+
Output: 1
116+
117+
Explanation:
118+
From the graph, we can clearly see that
119+
removing the edge 1-2 will result in
120+
disconnection of the graph. So, it is
121+
a bridge Edge and thus the Output 1.
122+
123+
*/

0 commit comments

Comments
 (0)