Check if a given Graph is 2-edge connected or not - GeeksforGeeks

30 Jun, 2021
Given an undirected graph G, with V vertices and E edges, the task is to check whether the graph is 2-edge connected or not.
A graph is said to be 2-edge connected if, on removing any edge of the graph, it still remains connected, i.e. it contains no Bridges.  
Examples: 
Input: V = 8, E = 10  
Output: Yes Explanation: Given any vertex in the graph, we can reach any other vertex in the graph. Moreover, removing any edge from the graph does not affect its connectivity. So, the graph is said to be 2-edge connected.
Input: V = 8, E = 9  
Output: No Explanation: On removal of the edge between vertex 3 and vertex 4, the graph is not connected anymore. So, the graph is not 2-edge connected. 
Naive Approach: The naive approach is to check that on removing any edge X, if the remaining graph G – X is connected or not. If the graph remains connected on removing every edge one by one then it is a 2-edge connected graph. To implement the above idea, remove an edge and perform Depth First Search(DFS) or Breadth-First Search(BFS) from any vertex and check if all vertices are covered or not. Repeat this process for all E edges. If all vertices cannot be traversed for any edge, print No. Otherwise, print Yes. 
Time Complexity: O(E * ( V + E)) Auxiliary Space: O(1) 
Efficient Approach: Since the given graph is undirected, the problem can be solved only by counting the number of edges connected to the nodes. If for any of the nodes, the number of edges connected to it is 1 it means on removing this edge the node becomes disconnected and it can’t be reached from any other node. Therefore, the graph is not 2-edge connected. Below are the steps: 
Create an array noOfEdges[] of size V which will store the number of edges connected to a node.For every edge (u, v) increment the number of edges for nodes u and v.Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected.Otherwise, the graph is 2-edge connected.
Create an array noOfEdges[] of size V which will store the number of edges connected to a node.
For every edge (u, v) increment the number of edges for nodes u and v.
Now iterate over the array noOfEdges[] and check if any of the edges has only 1 edge connected to it. If yes then the graph is not 2-edge connected.
Otherwise, the graph is 2-edge connected.
Below is the implementation of the above approach: 
C++14
Java
Python3
C#
Javascript
// C++14 program for the above approach #include <bits/stdc++.h>using namespace std; // Definition of a graphclass Graph {     // No. of vertices    int V;     // To create adjacency list    list<int>* adj; public:    // Constructor    Graph(int V);     // Function to add an edge to graph    void addEdge(int v, int w);     // Function to check 2-edge    // 2-edge connectivity    void twoEdge(int v);}; // Initialize the graphGraph::Graph(int V){    this->V = V;    adj = new list<int>[V];} // Adding edges to adjacency listvoid Graph::addEdge(int v, int w){    adj[v - 1].push_back(w - 1);    adj[w - 1].push_back(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid Graph::twoEdge(int v){    // To store number of edges for    // each node    int noOfEdges[v];     for (int i = 0; i < v; i++) {        noOfEdges[i] = adj[i].size();    }     bool flag = true;     // Check the number of edges    // connected to each node    for (int i = 0; i < v; i++) {         if (noOfEdges[i] < 2) {            flag = false;            break;        }    }     // Print the result    if (flag)        cout << "Yes";    else        cout << "No";} // Driver Codeint main(){    // Number of nodes and edges    int V = 8;    int E = 10;     // Given Edges    int edges[E][2] = { { 1, 2 }, { 1, 8 }, { 1, 6 },                        { 2, 3 }, { 2, 4 }, { 3, 7 },                        { 3, 4 }, { 7, 5 }, { 7, 6 },                        { 7, 8 } };     // Initialize the graph    Graph g(V);     // Adding the edges to graph    for (int i = 0; i < E; i++) {        g.addEdge(edges[i][0], edges[i][1]);    }     // Function call    g.twoEdge(V);     return 0;}
// Java program for the above approachimport java.util.*; class Graph{     // No. of vertices    private int V; // Array of lists for Adjacency// List Representationprivate LinkedList<Integer> adj[]; // Constructor@SuppressWarnings("unchecked")Graph(int v){    V = v;    adj = new LinkedList[v];         for(int i = 0; i < v; ++i)        adj[i] = new LinkedList();} // Function to add an edge into the graphvoid addEdge(int v, int w){    adj[v - 1].add(w - 1); // Add w to v's list.    adj[w - 1].add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){         // To store number of edges for    // each node    int[] noOfEdges = new int[v];    for(int i = 0; i < v; i++)    {        noOfEdges[i] = adj[i].size();    }     boolean flag = true;         // Check the number of edges    // connected to each node    for(int i = 0; i < v; i++)    {        if (noOfEdges[i] < 2)        {            flag = false;            break;        }    }         // Print the result    if (flag)        System.out.print("Yes");    else        System.out.print("No");} // Driver codepublic static void main (String[] args){         // Number of nodes and edges    int V = 8;    int E = 10;         // Given Edges    int edges[][] = { { 1, 2 }, { 1, 8 },                      { 1, 6 }, { 2, 3 },                      { 2, 4 }, { 3, 7 },                      { 3, 4 }, { 7, 5 },                      { 7, 6 }, { 7, 8 } };         Graph g = new Graph(V);         // Adding the edges to graph    for(int i = 0; i < E; i++)    {        g.addEdge(edges[i][0], edges[i][1]);    }         // Function call    g.twoEdge(V);}} // This code is contributed by offbeat
# Python3 program for the above approach # Definition of a graphclass Graph:     # No. of vertices    V = 0     # Array of lists for Adjacency    # List Representation    adj = [[]]     # Constructor    def __init__(self, v):                 self.V = v        self.adj = [[] for i in range(v)]     # Function to add an edge into the graph    def addEdge(self, v, w):             self.adj[v - 1].append(w - 1)                 # Add w to v's list.        self.adj[w - 1].append(v - 1)     # Function to find if the graph is    # 2 edge connected or not    def twoEdge(self, v):         # To store number of edges for        # each node        noOfEdges = [len(self.adj[i]) for i in range(v)]         flag = True         # Check the number of edges        # connected to each node        for i in range(v):            if (noOfEdges[i] < 2):                flag = False                break                     # Print the result        if (flag):            print("Yes")        else:            print("No")     # Driver codeif __name__=="__main__":     # Number of nodes and edges    V = 8    E = 10     # Given Edges    edges = [ [ 1, 2 ], [ 1, 8 ],              [ 1, 6 ], [ 2, 3 ],              [ 2, 4 ], [ 3, 7 ],              [ 3, 4 ], [ 7, 5 ],              [ 7, 6 ], [ 7, 8 ] ]     g = Graph(V)     # Adding the edges to graph    for i in range(E):        g.addEdge(edges[i][0],                  edges[i][1])         # Function call    g.twoEdge(V) # This code is contributed by rutvik_56
// C# program for the above approachusing System;using System.Collections.Generic; class Graph{     // No. of vertices    private int V; // Array of lists for Adjacency// List Representationprivate List<int> []adj; // ConstructorGraph(int v){    V = v;    adj = new List<int>[v];         for(int i = 0; i < v; ++i)        adj[i] = new List<int>();} // Function to add an edge into the graphvoid addEdge(int v, int w){         // Add w to v's list.    adj[v - 1].Add(w - 1);    adj[w - 1].Add(v - 1);} // Function to find if the graph is// 2 edge connected or notvoid twoEdge(int v){         // To store number of edges for    // each node    int[] noOfEdges = new int[v];    for(int i = 0; i < v; i++)    {        noOfEdges[i] = adj[i].Count;    }     bool flag = true;         // Check the number of edges    // connected to each node    for(int i = 0; i < v; i++)    {        if (noOfEdges[i] < 2)        {            flag = false;            break;        }    }         // Print the result    if (flag)        Console.Write("Yes");    else        Console.Write("No");} // Driver codepublic static void Main(String[] args){         // Number of nodes and edges    int V = 8;    int E = 10;         // Given Edges    int [,]edges = { { 1, 2 }, { 1, 8 },                     { 1, 6 }, { 2, 3 },                     { 2, 4 }, { 3, 7 },                     { 3, 4 }, { 7, 5 },                     { 7, 6 }, { 7, 8 } };         Graph g = new Graph(V);         // Adding the edges to graph    for(int i = 0; i < E; i++)    {        g.addEdge(edges[i, 0], edges[i, 1]);    }         // Function call    g.twoEdge(V);}} // This code is contributed by Amit Katiyar
<script>// Javascript program for the above approach      // No. of vertices    var V; // Array of lists for Adjacency// List Representationvar adj; // Constructorfunction initialize(v){    V = v;    adj = Array.from(Array(v), ()=>Array());} // Function to add an edge into the graphfunction addEdge(v, w){         // push w to v's list.    adj[v - 1].push(w - 1);    adj[w - 1].push(v - 1);} // Function to find if the graph is// 2 edge connected or notfunction twoEdge( v){         // To store number of edges for    // each node    var noOfEdges = Array(v)    for(var i = 0; i < v; i++)    {        noOfEdges[i] = adj[i].length;    }     var flag = true;         // Check the number of edges    // connected to each node    for(var i = 0; i < v; i++)    {        if (noOfEdges[i] < 2)        {            flag = false;            break;        }    }         // Print the result    if (flag)        document.write("Yes");    else        document.write("No");} // Driver code// Number of nodes and edgesvar V = 8;var E = 10; // Given Edgesvar edges = [ [ 1, 2 ], [ 1, 8 ],                 [ 1, 6 ], [ 2, 3 ],                 [ 2, 4 ], [ 3, 7 ],                 [ 3, 4 ], [ 7, 5 ],                 [ 7, 6 ], [ 7, 8 ] ]; initialize(V); // Adding the edges to graphfor(var i = 0; i < E; i++){    addEdge(edges[i][0], edges[i][1]);} // Function calltwoEdge(V); </script>
No
 
Time Complexity: O(V + E) Auxiliary Space: O(V) 
offbeat
amit143katiyar
rutvik_56
rrrtnx
BFS
DFS
Graph Traversals
Graph
Queue
Recursion
Searching
Searching
Recursion
DFS
Graph
Queue
BFS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Tree, Back, Edge and Cross Edges in DFS of Graph
Vertex Cover Problem | Set 1 (Introduction and Approximate Algorithm)
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Eulerian path and circuit for undirected graph
Find if there is a path between two vertices in a directed graph
Level Order Binary Tree Traversal
Queue Interface In Java
Queue in Python
Queue | Set 1 (Introduction and Array Implementation)
Queue - Linked List Implementation