Java Program to Find the Minimum Number of Edges to Remove to Disconnect a Graph

«
»
This is a java program to find bridges in a graph.

Here is the source code of the Java Program to Find Minimum Number of Edges to Cut to make the Graph Disconnected. The Java program is successfully compiled and run on a Windows system. The program output is also shown below.

  1.  
  2. package com.sanfoundry.hardgraph;
  3.  
  4. import java.util.Iterator;
  5. import java.util.NoSuchElementException;
  6. import java.util.Scanner;
  7. import java.util.Stack;
  8.  
  9. class Bag<Item> implements Iterable<Item>
  10. {
  11.     private int        N;    // number of elements in bag
  12.     private Node<Item> first; // beginning of bag
  13.  
  14.     // helper linked list class
  15.     private static class Node<Item>
  16.     {
  17.         private Item       item;
  18.         private Node<Item> next;
  19.     }
  20.  
  21.     public Bag()
  22.     {
  23.         first = null;
  24.         N = 0;
  25.     }
  26.  
  27.     public boolean isEmpty()
  28.     {
  29.         return first == null;
  30.     }
  31.  
  32.     public int size()
  33.     {
  34.         return N;
  35.     }
  36.  
  37.     public void add(Item item)
  38.     {
  39.         Node<Item> oldfirst = first;
  40.         first = new Node<Item>();
  41.         first.item = item;
  42.         first.next = oldfirst;
  43.         N++;
  44.     }
  45.  
  46.     public Iterator<Item> iterator()
  47.     {
  48.         return new ListIterator<Item>(first);
  49.     }
  50.  
  51.     // an iterator, doesn't implement remove() since it's optional
  52.     @SuppressWarnings("hiding")
  53.     private class ListIterator<Item> implements Iterator<Item>
  54.     {
  55.         private Node<Item> current;
  56.  
  57.         public ListIterator(Node<Item> first)
  58.         {
  59.             current = first;
  60.         }
  61.  
  62.         public boolean hasNext()
  63.         {
  64.             return current != null;
  65.         }
  66.  
  67.         public void remove()
  68.         {
  69.             throw new UnsupportedOperationException();
  70.         }
  71.  
  72.         public Item next()
  73.         {
  74.             if (!hasNext())
  75.                 throw new NoSuchElementException();
  76.             Item item = current.item;
  77.             current = current.next;
  78.             return item;
  79.         }
  80.     }
  81. }
  82.  
  83. class BridgeGraph
  84. {
  85.     private final int      V;
  86.     private int            E;
  87.     private Bag<Integer>[] adj;
  88.  
  89.     @SuppressWarnings("unchecked")
  90.     public BridgeGraph(int V)
  91.     {
  92.         if (V < 0)
  93.             throw new IllegalArgumentException(
  94.                     "Number of vertices must be nonnegative");
  95.         this.V = V;
  96.         this.E = 0;
  97.         adj = (Bag<Integer>[]) new Bag[V];
  98.         for (int v = 0; v < V; v++)
  99.         {
  100.             adj[v] = new Bag<Integer>();
  101.         }
  102.         System.out.println("Enter the number of edges: ");
  103.         Scanner sc = new Scanner(System.in);
  104.         int E = sc.nextInt();
  105.         if (E < 0)
  106.         {
  107.             sc.close();
  108.             throw new IllegalArgumentException(
  109.                     "Number of edges must be nonnegative");
  110.         }
  111.         for (int i = 0; i < E; i++)
  112.         {
  113.             int v = sc.nextInt();
  114.             int w = sc.nextInt();
  115.             addEdge(v, w);
  116.         }
  117.         sc.close();
  118.     }
  119.  
  120.     public BridgeGraph(BridgeGraph G)
  121.     {
  122.         this(G.V());
  123.         this.E = G.E();
  124.         for (int v = 0; v < G.V(); v++)
  125.         {
  126.             // reverse so that adjacency list is in same order as original
  127.             Stack<Integer> reverse = new Stack<Integer>();
  128.             for (int w : G.adj[v])
  129.             {
  130.                 reverse.push(w);
  131.             }
  132.             for (int w : reverse)
  133.             {
  134.                 adj[v].add(w);
  135.             }
  136.         }
  137.     }
  138.  
  139.     public int V()
  140.     {
  141.         return V;
  142.     }
  143.  
  144.     public int E()
  145.     {
  146.         return E;
  147.     }
  148.  
  149.     public void addEdge(int v, int w)
  150.     {
  151.         if (v < 0 || v >= V)
  152.             throw new IndexOutOfBoundsException();
  153.         if (w < 0 || w >= V)
  154.             throw new IndexOutOfBoundsException();
  155.         E++;
  156.         adj[v].add(w);
  157.         adj[w].add(v);
  158.     }
  159.  
  160.     public Iterable<Integer> adj(int v)
  161.     {
  162.         if (v < 0 || v >= V)
  163.             throw new IndexOutOfBoundsException();
  164.         return adj[v];
  165.     }
  166.  
  167.     public String toString()
  168.     {
  169.         StringBuilder s = new StringBuilder();
  170.         String NEWLINE = System.getProperty("line.separator");
  171.         s.append(V + " vertices, " + E + " edges " + NEWLINE);
  172.         for (int v = 0; v < V; v++)
  173.         {
  174.             s.append(v + ": ");
  175.             for (int w : adj[v])
  176.             {
  177.                 s.append(w + " ");
  178.             }
  179.             s.append(NEWLINE);
  180.         }
  181.         return s.toString();
  182.     }
  183. }
  184.  
  185. public class BridgesinGraph
  186. {
  187.     private int   bridges; // number of bridges
  188.     private int   cnt;    // counter
  189.     private int[] pre;    // pre[v] = order in which dfs examines v
  190.     private int[] low;    // low[v] = lowest preorder of any vertex connected
  191.                            // to v
  192.  
  193.     public BridgesinGraph(BridgeGraph G)
  194.     {
  195.         low = new int[G.V()];
  196.         pre = new int[G.V()];
  197.         for (int v = 0; v < G.V(); v++)
  198.             low[v] = -1;
  199.         for (int v = 0; v < G.V(); v++)
  200.             pre[v] = -1;
  201.         for (int v = 0; v < G.V(); v++)
  202.             if (pre[v] == -1)
  203.                 dfs(G, v, v);
  204.     }
  205.  
  206.     public int components()
  207.     {
  208.         return bridges + 1;
  209.     }
  210.  
  211.     private void dfs(BridgeGraph G, int u, int v)
  212.     {
  213.         pre[v] = cnt++;
  214.         low[v] = pre[v];
  215.         for (int w : G.adj(v))
  216.         {
  217.             if (pre[w] == -1)
  218.             {
  219.                 dfs(G, v, w);
  220.                 low[v] = Math.min(low[v], low[w]);
  221.                 if (low[w] == pre[w])
  222.                 {
  223.                     System.out.println(v + "-" + w + " is a bridge");
  224.                     bridges++;
  225.                 }
  226.             }
  227.             // update low number - ignore reverse of edge leading to v
  228.             else if (w != u)
  229.                 low[v] = Math.min(low[v], pre[w]);
  230.         }
  231.     }
  232.  
  233.     public static void main(String[] args)
  234.     {
  235.         Scanner sc = new Scanner(System.in);
  236.         System.out.println("Enter the number of vertices: ");
  237.         BridgeGraph G = new BridgeGraph(sc.nextInt());
  238.         System.out.println(G);
  239.         BridgesinGraph bridge = new BridgesinGraph(G);
  240.         System.out
  241.                 .println("Edge connected components = " + bridge.components());
  242.         sc.close();
  243.     }
  244. }

Output:

$ javac BridgesinGraph.ajav
$ java BridgesinGraph
 
Enter the number of vertices: 
6
Enter the number of edges: 
7
0 1
1 2
1 3
3 4
4 5
5 3
5 2
6 vertices, 7 edges 
0: 1 
1: 3 2 0 
2: 5 1 
3: 5 4 1 
4: 5 3 
5: 2 3 4 
 
0-1 is a bridge
Edge connected components = 2

Sanfoundry Global Education & Learning Series – 1000 Java Programs.

Sanfoundry Certification Contest of the Month is Live. 100+ Subjects. Participate Now!
advertisement
advertisement

Here’s the list of Best Books in Java Programming, Data Structures and Algorithms.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & technical discussions at Telegram SanfoundryClasses.