- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Program to Find Out the Edges that Disconnect the Graph in Python
Suppose we have been provided with an undirected graph that has been represented as an adjacency list, where graph[i] represents node i's neighbor nodes. We have to find the number of edges that satisfies the following condition.
If the edge is removed, the graph becomes disconnected.
So, if the input is like graph = [ [0, 2], [0, 4], [1, 2, 3], [0, 3, 4], [4], [3], [2] ],
then the output will be 1.
To solve this, we will follow these steps −
Define a function dfs(). This will take curr, pre, d
ans := infinity
dep[curr] := d
for each adj in graph[curr], do
if pre is same as adj, then
continue the next iteration without performing the other steps
if dep[adj] is not same as −1, then
ans := minimum of ans, dep[adj]
otherwise,
ans := minimum of ans, dfs(adj, curr, d + 1)
if d > 0 and d <= ans, then
re := re + 1
return ans
Now, from the main function call the function dfs().
dep := a list of the size of the graph initialized with −1.
re := 0
dfs(0, −1, 0)
return re
Let us see the following implementation to get better understanding −
Example
class Solution: def solve(self, graph): dep = [−1] * len(graph) INF = int(1e9) self.re = 0 def dfs(curr, pre, d): ans = INF dep[curr] = d for adj in graph[curr]: if pre == adj: continue if dep[adj] != −1: ans = min(ans, dep[adj]) else: ans = min(ans, dfs(adj, curr, d + 1)) if d > 0 and d <= ans: self.re += 1 return ans dfs(0, −1, 0) return self.re ob = Solution() print(ob.solve(graph = [ [0, 2], [0, 4], [1, 2, 3], [0, 3, 4], [4], [3], [2] ]))
Input
graph = [ [0, 2], [0, 4], [1, 2, 3], [0, 3, 4], [4], [3], [2] ]
Output
1