import java.util.*; class Edge { String startVertex; String endVertex; int value; } class MinHeap { Map<String, Integer> vertexVal; String[] verticesKeyArray; MinHeap(Map<String, Integer> vertexVal){ this.vertexVal = vertexVal; } public void heapify(String[] verticesArray,int root, int length) { int left = (2*root)+1; int right = (2*root)+2; int smallest = root; if (left < length && right <= length && vertexVal.get(verticesArray[right]) < vertexVal.get(verticesArray[left])) { smallest = right; } else if (left <= length){ smallest = left; } if (vertexVal.get(verticesArray[root]) > vertexVal.get(verticesArray[smallest])) { String temp = verticesArray[root]; verticesArray[root] = verticesArray[smallest]; verticesArray[smallest] = temp; heapify(verticesArray, smallest, length); } } public void buildHeap() { Set<String> verticesSet = vertexVal.keySet(); // Now convert the above keys to an Array. String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray); int len = verticesArray.length-1; for (int parent = (len-1)/ 2; parent >= 0; parent--) heapify(verticesArray, parent, len); verticesKeyArray = verticesArray; } public void updateHeap(String vertex, int length) { vertexVal.put(vertex, length); // Get all the keys (i.e. Vertices ) for the Map. Set<String> verticesSet = vertexVal.keySet(); // Now convert the above keys to an Array. String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray); int len = verticesArray.length-1; for (int parent = (len-1)/ 2; parent >= 0; parent--) heapify(verticesArray, parent, len); verticesKeyArray = verticesArray; } boolean containsVertex(String vertex){ if (vertexVal.containsKey(vertex)) return true; else return false; } public String deleteMin() { String temp = verticesKeyArray[0]; int len = verticesKeyArray.length-1; verticesKeyArray[0] = verticesKeyArray[len]; vertexVal.remove(temp); verticesKeyArray = Arrays.copyOf(verticesKeyArray, len); if (len>0) heapify(verticesKeyArray, 0, len-1); return temp; } int getWeight(String vertex){ return vertexVal.get(vertex); } public boolean empty() { if (verticesKeyArray.length>0) return false; else return true; } } public class PrimMST { LinkedList<String> vertices; LinkedList<LinkedList<Edge>> adjcList; Map<String,Integer> vertexVal; // Stores the Minimum spanning Tree List<Edge> result; PrimMST(){ adjcList = new LinkedList<>(); vertices = new LinkedList<>(); vertexVal = new LinkedHashMap<>(); // Stores the Minimum spanning Tree result = new ArrayList<>(); } public void primMST(){ vertexVal = new LinkedHashMap<>(); // Vertex to Edge Map Map<String, Edge> vertexToEdge = new HashMap<>(); // Assign all the initial values as infinity for all the Vertices. for(String v : vertices) { vertexVal.put(v,Integer.MAX_VALUE); } MinHeap minHeap = new MinHeap(vertexVal); // Call buildHeap() to create the MinHeap minHeap.buildHeap(); // Replace the value of start vertex to 0. minHeap.updateHeap("a",0); // Continue until the Min-Heap is not empty. while(!minHeap.empty()){ // Extract minimum value vertex from Map in Heap String currentVertex = minHeap.deleteMin(); // Need to get the edge for the vertex and add it to the Minimum Spanning Tree.. // Just note, the edge for the source vertex will not be added. Edge spanningTreeEdge = vertexToEdge.get(currentVertex); if(spanningTreeEdge != null) { result.add(spanningTreeEdge); } // Get all the adjacent vertices and iterate through them. for(Edge edge : getEdges(currentVertex)){ String adjacentVertex = edge.endVertex; // We check if adjacent vertex exist in 'Map in Heap' and length of the edge is with this vertex // is greater than this edge length. if(minHeap.containsVertex(adjacentVertex) && minHeap.getWeight(adjacentVertex) > edge.value){ // Replace the edge length with this edge weight. minHeap.updateHeap(adjacentVertex, edge.value); vertexToEdge.put(adjacentVertex, edge); } } } } List<Edge> getEdges(String vertex){ List<Edge> edgeList = new LinkedList<>(); int i = vertices.indexOf(vertex); for (Iterator iter = adjcList.get(i).iterator() ; iter.hasNext(); ) { edgeList.add((Edge) iter.next()); } return edgeList; } void constructAdjacencyList(String vertex1, String vertex2, int edgeVal) { Edge edge = new Edge(); edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal; adjcList.add(new LinkedList<Edge>()); adjcList.get(vertices.indexOf(vertex1)).add(edge); } void insertVertex(String vertex) { vertices.add(vertex); } void printEdgeList() { for (Edge edge : result) { System.out.println("The Edge between "+edge.startVertex+" and "+edge.endVertex+" is "+edge.value ); } } public static void main(String[] args) { PrimMST primMST = new PrimMST(); // Insert Vertices primMST.insertVertex("a"); primMST.insertVertex("b"); primMST.insertVertex("c"); primMST.insertVertex("d"); primMST.insertVertex("e"); // Create Adjacency List with Edges. primMST.constructAdjacencyList("a", "b",1); primMST.constructAdjacencyList("a", "c",5); primMST.constructAdjacencyList("a", "d",4); primMST.constructAdjacencyList("b", "a",1); primMST.constructAdjacencyList("b" ,"e",8); primMST.constructAdjacencyList("c", "a",5); primMST.constructAdjacencyList("c", "d",12); primMST.constructAdjacencyList("c", "e",9); primMST.constructAdjacencyList("d", "a", 4); primMST.constructAdjacencyList("d", "c", 12); primMST.constructAdjacencyList("d", "e", 3); primMST.constructAdjacencyList("e", "b", 8); primMST.constructAdjacencyList("e", "c", 9); primMST.constructAdjacencyList("e", "d", 3); primMST.primMST(); primMST.printEdgeList(); } }
Let us recapitulate the 3 step process for Prim's Algorithm :
Let us take the below graph, to understand the above code.
The first task is to construct the Graph. So, we need to store the Vertices first.
LinkedList<String> vertices;
And also we know, we have to represent the edges as 'Adjacency List'.
LinkedList<LinkedList<Edge>> adjcList;
Eventually, in the 'main(...)' method. We have initialised the vertices,
primMST.insertVertex("a"); primMST.insertVertex("b"); primMST.insertVertex("c"); primMST.insertVertex("d"); primMST.insertVertex("e");
And, created the 'Adjacency List' with Edges.
// Create Adjacency List with Edges. primMST.constructAdjacencyList("a", "b", 1); primMST.constructAdjacencyList("a", "c", 5); primMST.constructAdjacencyList("a", "d", 4); primMST.constructAdjacencyList("b", "a", 1); primMST.constructAdjacencyList("b" ,"e", 8); primMST.constructAdjacencyList("c", "a", 5); primMST.constructAdjacencyList("c", "d", 12); primMST.constructAdjacencyList("c", "e", 9); primMST.constructAdjacencyList("d", "a", 4); primMST.constructAdjacencyList("d", "c", 12); primMST.constructAdjacencyList("d", "e", 3); primMST.constructAdjacencyList("e", "b", 8); primMST.constructAdjacencyList("e", "c", 9); primMST.constructAdjacencyList("e", "d", 3);
Let us understand creation process of Adjacency List. If you already know it, you can skip.
Click Here - For the creation process of Adjacency List.
void constructAdjacencyList(String vertex1, String vertex2, int edgeVal) { Edge edge = new Edge(); edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal; adjcList.add(new LinkedList<Edge>()); adjcList.get(vertices.indexOf(vertex1)).add(edge); } void insertVertex(String vertex) { vertices.add(vertex); }
Let us take the example of the Edge (a,b) with length 1 and understand the above code.
primMST.constructAdjacencyList("a", "b", 1);
Now, if we look at the method definition,
void constructAdjacencyList(String vertex1, String vertex2, int edgeVal) 'String vertex1' is initialised with 'a'. 'String vertex2' is initialised with 'b'. 'int edgeVal' is initialised with '1'.
The next thing we do is, create an 'Edge' object.
Edge edge = new Edge();
And initialise the 'Edge edge' object with the start vertex, end vertex and the length of the Edge.
edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal;
And the Edge object looks somewhat like,
Now, since we have the Edge (a,b) initialised. The next task would be, to add this Edge to the AdjacencyList.
And as we have seen, there is a 2D LinkedList to store the Adjacency List.
LinkedList<LinkedList<Edge>> adjcList;
Now, we will be creating the first row of LinkedList,
adjcList.add(new LinkedList<Edge>());
And then we will try finding out, for which vertex we are going to insert the Edge.
adjcList.get(vertices.indexOf(vertex1)).add(edge);
In simple words, 'vertices.indexOf(vertex1)' will tell us about the position of the start vertex.
In this case, the start vertex is 'a'. And 'vertices.indexOf(vertex1)' will tell us about its position, i.e. 0.
So, if we substitute the line,
adjcList.get(vertices.indexOf(vertex1)).add(edge);
With the value of 'vertices.indexOf(vertex1)',
adjcList.get(0).add(edge);
The 'edge' would be added to the 0th location of the 2d LinkedList.
This is how a 2D LinkedList looks like. Just remember, the empty blocks are not yet created, but will be created eventually.
For now, only the first row is created with the first column where the edge
is inserted.
Next, when we try to insert the second adjacent edge of a i.e. a,c.
primMST.constructAdjacencyList("a", "c", 5);
An edge object will be created
edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal;
And the Edge object looks somewhat like,
Once again the start vertex is 'a'. And 'vertices.indexOf(vertex1)' will tell us about its position, i.e. 0.
So, if we substitute the line,
adjcList.get(vertices.indexOf(vertex1)).add(edge);
With the value of 'vertices.indexOf(vertex1)',
adjcList.get(0).add(edge);
The 'edge' would be added to the 1st row of the 2d LinkedList, just next to the first edge.
Similarly, we insert the third adjacent edge of 'a' i.e. a,d.
primMST.constructAdjacencyList("a", "d", 4);
An edge object will be created
edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal;
And the Edge object looks somewhat like,
Once again the start vertex is 'a'. And 'vertices.indexOf(vertex1)' will tell us about its position, i.e. 0.
So, if we substitute the line,
adjcList.get(vertices.indexOf(vertex1)).add(edge);
With the value of 'vertices.indexOf(vertex1)',
adjcList.get(0).add(edge);
The 'edge' would be added to the 1st row of the 2d LinkedList, just next to the first edge.
Similarly, we insert the adjacent edge of 'b' i.e. b,a.
primMST.constructAdjacencyList("b", "a", 1);
An edge object will be created
edge.startVertex = vertex1; edge.endVertex = vertex2; edge.value = edgeVal;
And the Edge object looks somewhat like,
Now, the start vertex is 'b'. And 'vertices.indexOf(vertex1)' will tell us about its position, i.e. 1.
So, if we substitute the line,
adjcList.get(vertices.indexOf(vertex1)).add(edge);
With the value of 'vertices.indexOf(vertex1)',
adjcList.get(1).add(edge);
And this time, the 'edge' would be added to the 2nd row of the 2d LinkedList.
And eventually the AdjacencyList with Edges would be created with the 2D LinkedList.
Once we are done creating the AdjacencyList with Edges. The next task would be to call the actual method for Prim's Algorithm,
primMST.primMST();
Before we understand 'primMST()' method in detail. Let us understand the Min-Heap Data Structure.
If you already know Min-Heap Data Structure, you can skip the below part.
Click Here - For Min-Heap Data Structure Recap.
There are four important method in the MinHeap class that are quite important.
They are :
Now, if we look at the 'primMST()' method, we could see that initially the MinHeap object is created using a parameterised constructor.
MinHeap minHeap = new MinHeap(vertexVal);
And if we look at the Constructor definition,
MinHeap(Map<String, Integer> vertexVal){ this.vertexVal = vertexVal; }
The Map 'Map<String, Integer> vertexVal' is getting initialised here.
this.vertexVal = vertexVal;
Where, 'this.vertexVal' is the class attribute,
Map<String, Integer> vertexVal;
Next, we initialise the Map with the vertices as key and assign the value as Integer.MAX_VALUE. This 'Integer.MAX_VALUE' is so large that it could be compared with infinity.
// Assign all the initial values as infinity for all the Vertices. for(String v : vertices) { vertexVal.put(v,Integer.MAX_VALUE); }
So, the Map 'vertexVal' is loaded with values.
Next, we call the 'buildHeap()' method to create the MinHeap, with the values of the Map 'vertexVal'.
minHeap.buildHeap();
public void buildHeap() { Set<String> verticesSet = vertexVal.keySet(); // Now convert the above keys to an Array. String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray); int len = verticesArray.length-1; for (int parent = (len-1)/ 2; parent >= 0; parent--) heapify(verticesArray, parent, len); verticesKeyArray = verticesArray; }
Just remember, Map is not a good Data Structure for Heap. Whereas array is an excellent Data Structure for Heap.
So, we take the keys from the Map and create an Array out of it.
To do this, there is a two step process involved.
First, we extract the key from the Map and put it into a Set.
Set<String> verticesSet = vertexVal.keySet();
Second, we create an Array and convert the Set to the Array.
String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray);
Then, we take the length of the Array.
int len = verticesArray.length-1;
Then, we divide the Array into two parts and run a 'for' loop. Then call the Heapify method.
for (int parent = (len-1)/ 2; parent >= 0; parent--) heapify(verticesArray, parent, len);
So, what does the heapify(..) method do?
Let us see.
public void heapify(String[] verticesArray,int root, int length) { int left = (2*root)+1; int right = (2*root)+2; int smallest = root; if (left < length && right <= length && vertexVal.get(verticesArray[right]) < vertexVal.get(verticesArray[left])) { smallest = right; } else if (left <= length){ smallest = left; } if (vertexVal.get(verticesArray[root]) > vertexVal.get(verticesArray[smallest])) { String temp = verticesArray[root]; verticesArray[root] = verticesArray[smallest]; verticesArray[smallest] = temp; heapify(verticesArray, smallest, length); } }
Since, all the values of the Map 'vertexVal' are infinity now. So, it doesn't matter how the values will be inserted in the Min-Heap.
For the sake of understanding, let us understand the functionality of 'heapify(...)' method.
So, we have passed the 'verticesArray', 'root' element and the 'length' of the Array to 'heapify(...)' method.
Then, we have calculated the left, right and root element of the Heap.
int left = (2*root)+1; int right = (2*root)+2; int smallest = root;
Since, this is a Min-Heap. The smallest element would be at the root of the Heap.
So, we try initialising the 'smallest' element with its right value.
And the below 'if' condition checks, if the 'left' and 'right' element is less than the length of the Array.
if (left < length && right <= length && vertexVal.get(verticesArray[right]) < vertexVal.get(verticesArray[left])) { smallest = right; } else if (left <= length){ smallest = left; }
And, if the element on the right side of the Map 'vertexVal' is less than the element on the right side.
vertexVal.get(verticesArray[right]) < vertexVal.get(verticesArray[left])
Then element on the right side of the Map is the smallest element.
smallest = right;
And in the else part, we can assume that the element on the left side of the Map has the smallest element.
smallest = left;
Now, since we got the smallest element. We need to check if the actual 'root' element is greater than the 'smallest' element or not.
if (vertexVal.get(verticesArray[root]) > vertexVal.get(verticesArray[smallest])) { String temp = verticesArray[root]; verticesArray[root] = verticesArray[smallest]; verticesArray[smallest] = temp; heapify(verticesArray, smallest, length); }
And this is where, we swap the contents of the 'root' element and the 'smallest' element. Assuming the element in the root is greater than the smallest element.
Which shouldn't be. As the root element should always be the smallest element.
Then a recursive call is made to heapify(...) method.
heapify(verticesArray, smallest, length);
And the recursion continues until all the elements are arranged in MinHeap.
In the next line, we would update the value of source element 'a' to 0.
// Replace the value of start vertex to 0. minHeap.updateHeap("a",0);
Now, if we see the updateHeap(...) method,
public void updateHeap(String vertex, int length) { vertexVal.put(vertex, length); // Get all the keys (i.e. Vertices ) for the Map. Set<String> verticesSet = vertexVal.keySet(); // Now convert the above keys to an Array. String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray); int len = verticesArray.length-1; for (int parent = (len-1)/ 2; parent >= 0; parent--) heapify(verticesArray, parent, len); verticesKeyArray = verticesArray; }
The first thing we do is, replace the value in the Map 'vertexVal'.
vertexVal.put(vertex, length);
Then we follow the same process we followed above. i.e. Extract the keys from the Map. Make it a Set and then convert the Set into an Array.
Set<String> verticesSet = vertexVal.keySet(); String[] verticesArray = new String[verticesSet.size()]; verticesSet.toArray(verticesArray);
Then we call the heapify(...) method. Because we have updated a new value and in that case the Heap has to be rearranged to form a Min-Heap.
Now, that we have understood Min-Heap. Let us understand the details about the actual method that calculates the Minimum Spanning Tree using Prim's Algorithm.
public void primMST(){ vertexVal = new LinkedHashMap<>(); // Vertex to Edge Map Map<String, Edge> vertexToEdge = new HashMap<>(); // Assign all the initial values as infinity for all the Vertices. for(String v : vertices) { vertexVal.put(v,Integer.MAX_VALUE); } MinHeap minHeap = new MinHeap(vertexVal); // Call buildHeap() to create the MinHeap minHeap.buildHeap(); // Replace the value of start vertex to 0. minHeap.updateHeap("a",0); // Continue until the Min-Heap is not empty. while(!minHeap.empty()){ // Extract minimum value vertex from Map in Heap String currentVertex = minHeap.deleteMin(); // Need to get the edge for the vertex and add it to the Minimum Spanning Tree.. // Just note, the edge for the source vertex will not be added. Edge spanningTreeEdge = vertexToEdge.get(currentVertex); if(spanningTreeEdge != null) { result.add(spanningTreeEdge); } // Get all the adjacent vertices and iterate through them. for(Edge edge : getEdges(currentVertex)){ String adjacentVertex = edge.endVertex; // We check if adjacent vertex exist in 'Map in Heap' and length of the edge is with this vertex // is greater than this edge length. if(minHeap.containsVertex(adjacentVertex) && minHeap.getWeight(adjacentVertex) > edge.value){ // Replace the edge length with this edge weight. minHeap.updateHeap(adjacentVertex, edge.value); vertexToEdge.put(adjacentVertex, edge); } } } }
Three things to remember :
Map<String,Integer> vertexVal;
Map<String, Edge> vertexToEdge;
List<Edge> result;
Now, let us look at the steps involved :
vertexVal = new LinkedHashMap<>();
Map<String, Edge> vertexToEdge = new HashMap<>();
for(String v : vertices) { vertexVal.put(v,Integer.MAX_VALUE); }
MinHeap minHeap = new MinHeap(vertexVal);
minHeap.buildHeap();
minHeap.buildHeap();
while(!minHeap.empty()){ // Extract minimum value vertex from Map in Heap String currentVertex = minHeap.deleteMin(); // Need to get the edge for the vertex and add it to the Minimum Spanning Tree. // Just note, the edge for the source vertex will not be added. Edge spanningTreeEdge = vertexToEdge.get(currentVertex); if(spanningTreeEdge != null) { result.add(spanningTreeEdge); } // Get all the adjacent vertices and iterate through them. for(Edge edge : getEdges(currentVertex)){ String adjacentVertex = edge.endVertex; // We check if adjacent vertex exist in 'Map in Heap' and length of the edge is with this vertex // is greater than this edge length. if(minHeap.containsVertex(adjacentVertex) && minHeap.getWeight(adjacentVertex) > edge.value){ // Replace the edge length with this edge weight. minHeap.updateHeap(adjacentVertex, edge.value); vertexToEdge.put(adjacentVertex, edge); } } }
String currentVertex = minHeap.deleteMin();
Edge spanningTreeEdge = vertexToEdge.get(currentVertex); if(spanningTreeEdge != null) { result.add(spanningTreeEdge); }
for(Edge edge : getEdges(currentVertex)){ String adjacentVertex = edge.endVertex; // We check if adjacent vertex exist in 'Map in Heap' and length of the edge associated with this vertex // is greater than this edge length. if(minHeap.containsVertex(adjacentVertex) && minHeap.getWeight(adjacentVertex) > edge.value){ // Replace the edge length with this edge weight. minHeap.updateHeap(adjacentVertex, edge.value); vertexToEdge.put(adjacentVertex, edge); } }
String adjacentVertex = edge.endVertex;
if(minHeap.containsVertex(adjacentVertex) && minHeap.getWeight(adjacentVertex) > edge.value){ minHeap.updateHeap(adjacentVertex, edge.value); vertexToEdge.put(adjacentVertex, edge); }
minHeap.updateHeap(adjacentVertex, edge.value);
vertexToEdge.put(adjacentVertex, edge);
The time complexity of Prim's Algorithm for Minimum Spanning Tree is : O(E logV)
Where E is the Edge And V is the Vertex
The time complexity O(E logV) is only when we will be using the above combination of MIn-Heap and Adjacency List.