-
Notifications
You must be signed in to change notification settings - Fork 171
/
Copy pathMST.java
142 lines (114 loc) · 2.15 KB
/
MST.java
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
class Stack {
private int[] a;
private int ele;
private int size;
public Stack(int size) {
a = new int[size];
this.size = size;
ele = -1;
}
public void push(int val) {
ele++;
a[ele] = val;
}
public void pop() {
ele--;
}
public boolean isEmpty() {
if(ele == -1) return true;
else return false;
}
public int top() {
return a[ele];
}
}
class Vertex {
int label;
boolean isVisited;
Vertex(int label) {
this.label = label;
isVisited = false;
}
}
class Graph {
private Vertex V[];
private int vMax;
private int[][] adjMat;
public int nV;
private Stack s;
Graph(int vMax) {
this.vMax = vMax; // Maximum vertex can vbe added
nV = 1; // counter for the vertices we will work with 1
V = new Vertex[vMax + 1];
adjMat = new int[vMax + 1][vMax + 1];
s = new Stack(V.length);
}
public void addVertix(int label) {
V[nV] = new Vertex(label);
nV++;
}
public void addEdge(int s, int d) {
adjMat[s][d] = 1;
adjMat[d][s] = 1;
}
public int unVisitedAdjVet(int v) {
for(int i=1; i<nV; i++) {
if( adjMat[v][i] == 1 && !V[i].isVisited )
return i;
}
return -1;
}
public void mst(int start) {
s.push(start);
V[start].isVisited = true;
while(!s.isEmpty()) {
int curVet = s.top();
int vet = unVisitedAdjVet(curVet);
if(vet == -1) {
s.pop();
} else {
V[vet].isVisited = true;
s.push(vet);
System.out.println(V[curVet].label + "-" + V[vet].label);
}
}
}
}
class MST {
public static void main(String[] args) {
Graph g = new Graph(5);
g.addVertix(1);
g.addVertix(2);
g.addVertix(3);
g.addVertix(4);
g.addVertix(5);
// This is K5 graph : https://bit.ly/2Dnfevl
g.addEdge(1, 2);
g.addEdge(1, 3);
g.addEdge(1, 4);
g.addEdge(1, 5);
g.addEdge(2, 3);
g.addEdge(2, 4);
g.addEdge(2, 5);
g.addEdge(3, 4);
g.addEdge(3, 5);
g.addEdge(4, 5);
g.mst(1);
/*
1
/
2 -- 3
/
4 -- 5
*/
//To get this output make sure to comment g.mst(1)
g.mst(2);
/*
1
/ \
2 3
/
4 -- 5
*/
}
}