Skip to content

Commit 413d256

Browse files
authored
Merge pull request larissalages#264 from UmaMaheswariGorusupudi/master
Added solution for a edges on graph problem in hacker earth
2 parents 8a34fde + d66a42a commit 413d256

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed
Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
from collections import defaultdict
2+
from collections import deque
3+
4+
5+
#the solution is simple find the brige edges in the graph first
6+
#find a path form a to b and check for the bridge edges in the and count them.
7+
8+
9+
#class for finding bridge edges
10+
class Graph:
11+
12+
#basic structure of graph
13+
def __init__(self,vertices):
14+
self.V = vertices
15+
self.graph = defaultdict(list)
16+
self.Time = 0
17+
self.ans = []
18+
19+
#to add a edge
20+
def addEdge(self,u,v):
21+
self.graph[u].append(v)
22+
self.graph[v].append(u)
23+
24+
#helper function for finding bridge edges
25+
def bridgeUtil(self,u,visited,parent,low,disc):
26+
27+
visited[u] = True
28+
disc[u] = self.Time
29+
low[u] = self.Time
30+
self.Time +=1
31+
32+
for v in self.graph[u]:
33+
34+
if visited[v] == False:
35+
parent[v] = u
36+
self.bridgeUtil(v,visited,parent,low,disc)
37+
38+
low[u] = min(low[u],low[v])
39+
40+
if(low[v]>disc[u]):
41+
#finally found the bridge edge
42+
self.ans.append([u,v])
43+
#print(u,v)
44+
45+
elif v!=parent[u]:
46+
low[u] = min(low[u],disc[v])
47+
48+
#function to call helper function with initial inputs
49+
def bridge(self):
50+
51+
visited = [False] * (self.V)
52+
disc = [float("Inf")] * (self.V)
53+
low = [float("Inf")] * (self.V)
54+
parent = [-1] * (self.V)
55+
56+
for i in range(self.V):
57+
if visited[i] == False:
58+
self.bridgeUtil(i,visited,parent,low,disc)
59+
60+
#path function returns parent array
61+
#this function uses dfs for finding the path
62+
#parent arr means for given edge V -- > u in arr[u] = v
63+
64+
def path(self,x,y):
65+
q = deque()
66+
visited = [False] * (self.V)
67+
q.append(x)
68+
parent = [-1] * (self.V)
69+
while(len(q)>0):
70+
u = q.popleft()
71+
for v in self.graph[u]:
72+
if(v == y):
73+
visited[v] = True
74+
parent[v] = u
75+
return parent
76+
if(visited[v] == False):
77+
q.append(v)
78+
visited[v] = True
79+
parent[v] = u
80+
81+
82+
83+
if __name__ == '__main__':
84+
n,m = map(int,input().split())
85+
a,b = map(int,input().split())
86+
g1 = Graph(n)
87+
count = 0
88+
for i in range(m):
89+
x,y = map(int,input().split())
90+
g1.addEdge(x-1, y-1)
91+
g1.bridge()
92+
p = g1.path(a-1,b-1)
93+
pa = []
94+
u = b-1
95+
96+
#checking for the bridge edegs in the path
97+
while(u != a-1):
98+
pa.append([u,p[u]])
99+
pa.append([p[u],u])
100+
u = p[u]
101+
102+
for i in g1.ans:
103+
if(i in pa):
104+
count = count + 1
105+
print(count)

0 commit comments

Comments
 (0)