Repository navigation
Expand file tree
/
Copy pathGraphPrims.java
More file actions
64 lines (52 loc) · 1.67 KB
/
Copy pathGraphPrims.java
File metadata and controls
64 lines (52 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
//MST using Prim's Algorithm
import java.util.*;
public class GraphPrims {
private int[][] adjMatrix;
private int vertexCount;
public GraphPrims(int vertices) {
vertexCount = vertices;
adjMatrix = new int[vertices][vertices];
}
public void addEdge(int i, int j, int w) {
adjMatrix[i][j] = w;
adjMatrix[j][i] = w;
}
public int primMSTCost() {
int[] key = new int[vertexCount];
boolean[] mstSet = new boolean[vertexCount];
Arrays.fill(key, Integer.MAX_VALUE);
key[0] = 0;
int mstCost = 0;
for (int count = 0; count < vertexCount; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
mstCost += key[u];
for (int v = 0; v < vertexCount; v++) {
if (adjMatrix[u][v] != 0 && !mstSet[v] && adjMatrix[u][v] < key[v]) {
key[v] = adjMatrix[u][v];
}
}
}
return mstCost;
}
private int minKey(int[] key, boolean[] mstSet) {
int min = Integer.MAX_VALUE, minIndex = -1;
for (int v = 0; v < vertexCount; v++) {
if (!mstSet[v] && key[v] < min) {
min = key[v];
minIndex = v;
}
}
return minIndex;
}
public static void main(String[] args) {
GraphPrims graph = new GraphPrims(5);
graph.addEdge(0, 1, 4);
graph.addEdge(1, 4, 6);
graph.addEdge(4, 3, 10);
graph.addEdge(3, 2, 2);
graph.addEdge(0, 2, 8);
int mstCost = graph.primMSTCost();
System.out.println("Total MST Cost (Prim's): " + mstCost);
}
}