Commit 981d38ed authored by Moritz Leibauer's avatar Moritz Leibauer
Browse files

implemented Prim

parent 42ae9e27
...@@ -37,7 +37,60 @@ public class mySpanningTree { ...@@ -37,7 +37,60 @@ public class mySpanningTree {
} }
public static AsSubgraph<Integer, DefaultWeightedEdge> primAlgorithm(AsSubgraph<Integer, DefaultWeightedEdge> tree, Graph<Integer, DefaultWeightedEdge> graph) { public static AsSubgraph<Integer, DefaultWeightedEdge> primAlgorithm(AsSubgraph<Integer, DefaultWeightedEdge> tree, Graph<Integer, DefaultWeightedEdge> graph) {
// Input: tree -> // begin
// Set F = 0 -> Schon geschehen
Set<Integer> V = graph.vertexSet();
Set<DefaultWeightedEdge> E = graph.edgeSet();
// choose w in V and define X = {w}
int start_vertex = 1; // <- Wird bei Prim ja eigentlich beliebig gewählt, nicht?
Set<Integer> X = new HashSet<Integer>();
X.add(start_vertex);
// while X != V do
while (X.size() != V.size()) {
// choose an edge {u,v} in E of smallest possible weight with u € X and v € V \ X
DefaultWeightedEdge uv = new DefaultWeightedEdge(); // edge with smallest_possible weight
double uv_weight = Double.MAX_VALUE;
Iterator<Integer> X_it = X.iterator(); // iterate over set vertices
while (X_it.hasNext()) {
int u = X_it.next();
Set<DefaultWeightedEdge> outgoing_edges = graph.outgoingEdgesOf(u); // get outgoing edges of set vertex
Iterator<DefaultWeightedEdge> outgoing_it = outgoing_edges.iterator(); // iterate over outgoing edges
while (outgoing_it.hasNext()) {
DefaultWeightedEdge e = outgoing_it.next();
int target = graph.getEdgeTarget(e);
if (target == u) {
target = graph.getEdgeSource(e);
}
if (!X.contains(target)) { // check that edge target vertex isn't already set
double weight = graph.getEdgeWeight(e);
if (weight < uv_weight) {
uv = e;
uv_weight = weight;
}
}
}
}
// put {u,v} in F
int source = graph.getEdgeSource(uv);
int target = graph.getEdgeTarget(uv);
if (X.contains(target)) {
source = target;
target = graph.getEdgeSource(uv);
}
tree.addEdge(source, target);
tree.setEdgeWeight(source, target, uv_weight);
// put v in X
X.add(target);
}
return tree; return tree;
} }
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment