import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class DisJointGraph {
static Map<Integer, List<Integer>> graph;
private static Integer noOfVertices = 5;
static {
graph = new HashMap<>();
for (int i = 1; i <= noOfVertices; i++)
graph.put(i, new ArrayList<>());
}
private static void setEdge(Integer verticeA, Integer verticeB) throws Exception {
if (!graph.containsKey(verticeA)) {
throw new Exception("Vertice does not exist");
}
List<Integer> l = graph.get(verticeA);
l.add(verticeB);
graph.put(verticeA, l);
}
private static List<Entry<Integer, List<Integer>>> sortByValue() {
Set<Entry<Integer, List<Integer>>> entrySet = graph.entrySet();
List<Entry<Integer, List<Integer>>> list = new ArrayList<>(entrySet);
Collections.sort(list,
(o1, o2) -> new Integer(o1.getValue().size()).compareTo(new Integer(o2.getValue().size())));
return list;
}
private static void removeEdge() {
List<Entry<Integer, List<Integer>>> list = sortByValue();
System.out.println("Sorting List of Vertices and Edges in Reverse order of min edges :: ");
System.out.println(list);
graph.remove(list.get(0).getKey());
}
private static void printGraph() {
System.out.println(graph);
}
public static void main(String[] args) throws Exception {
setEdge(1, 2);
setEdge(1, 3);
setEdge(2, 3);
setEdge(2, 4);
setEdge(2, 5);
setEdge(3, 1);
setEdge(3, 2);
setEdge(3, 5);
setEdge(4, 2);
setEdge(5, 2);
setEdge(5, 3);
System.out.println("Input Graph Vertices and Edges :: ");
printGraph();
removeEdge();
System.out.println("Output Graph after remove the edge and making the graph disjoint :: ");
System.out.println(graph);
}
}
Output:
Input Graph Vertices and Edges ::
{1=[2, 3], 2=[3, 4, 5], 3=[1, 2, 5], 4=[2], 5=[2, 3]}
Sorting List of Vertices and Edges in Reverse order of min edges ::
[4=[2], 1=[2, 3], 5=[2, 3], 2=[3, 4, 5], 3=[1, 2, 5]]
Output Graph after remove the edge and making the graph disjoint ::
{1=[2, 3], 2=[3, 4, 5], 3=[1, 2, 5], 5=[2, 3]}