Skip to content

Commit dcfabc5

Browse files
committed
feat: 크루스칼 알고리즘 구현
1 parent e27b4dd commit dcfabc5

File tree

1 file changed

+66
-1
lines changed

1 file changed

+66
-1
lines changed

yoonexample/src/main/java/graph/ListWeightGraph.java

Lines changed: 66 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,73 @@ public String showGraphEdgeWeightInfo() {
5757

5858
@Override
5959
public void convertToMST() {
60+
int vertexCount = this.vertices.length;
61+
int edgeCount = this.edgePriorityQueue.size() + 1;
62+
List<WeightEdge> edges = new DummyDoublyLinkedList<>();
6063

64+
// MST가 될 때까지 while문을 반복
65+
while (edgeCount != vertexCount) {
66+
WeightEdge edge = this.edgePriorityQueue.dequeue();
67+
removeEdge(edge.fromVertex, edge.toVertex); // 그래프에서 제거해본다.
68+
edgeCount--;
69+
70+
if (!isConnectedWith(edge.fromVertex, edge.toVertex)) { // 연결되어 있지 않으면 복구
71+
recoverEdge(edge);
72+
edges.insert(edge);
73+
edgeCount++;
74+
}
75+
}
76+
77+
// 간선 정보 복원
78+
for (int i = 0; i < edges.size(); i++) {
79+
this.edgePriorityQueue.enqueue(edges.get(i));
80+
}
81+
}
82+
83+
private boolean isConnectedWith(Enum<?> fromVertex, Enum<?> toVertex) {
84+
boolean[] visited = new boolean[vertices.length];
85+
Stack<Enum<?>> vertexStack = new ListStack<>();
86+
vertexStack.push(fromVertex);
87+
88+
while (!vertexStack.isEmpty()) {
89+
Enum<?> visitV = vertexStack.pop();
90+
if (visitVertex(visited, visitV)) {
91+
if (visitV.equals(toVertex)) {
92+
return true;
93+
}
94+
}
95+
96+
List<Enum<?>> vertexList = vertices[visitV.ordinal()];
97+
for (int i = 0; i < vertexList.size(); i++) {
98+
Enum<?> vertex = vertexList.get(i);
99+
if (!visited[vertex.ordinal()]) {
100+
vertexStack.push(vertex);
101+
}
102+
}
103+
}
104+
105+
return false;
106+
}
107+
108+
private void recoverEdge(WeightEdge edge) {
109+
vertices[edge.fromVertex.ordinal()].insert(edge.toVertex);
110+
vertices[edge.toVertex.ordinal()].insert(edge.fromVertex);
111+
}
112+
113+
private void removeEdge(Enum<?> fromVertex, Enum<?> toVertex) {
114+
removeVertexFromLink(fromVertex, toVertex);
115+
removeVertexFromLink(toVertex, fromVertex);
116+
}
117+
118+
private void removeVertexFromLink(Enum<?> vertexA, Enum<?> vertexB) {
119+
List<Enum<?>> vertexLinkInfo = this.vertices[vertexA.ordinal()];
120+
for (int i = 0; i < vertexLinkInfo.size(); i++) {
121+
if (vertexLinkInfo.get(i).equals(vertexB)) {
122+
vertexLinkInfo.remove(i);
123+
return;
124+
}
125+
}
126+
throw new IllegalArgumentException("해당 정점들은 연결되어있지 않습니다.");
61127
}
62128

63129
@Override
@@ -132,7 +198,6 @@ public String breadthFirstSearch(Enum<?> startV) {
132198
vertexQueue.enqueue(vertex);
133199
}
134200
}
135-
136201
}
137202

138203
return sj.toString();

0 commit comments

Comments
 (0)