Skip to content
GitLab
Menu
Projects
Groups
Snippets
/
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Sign in
Toggle navigation
Menu
Open sidebar
Moritz Leibauer
Opti B - Prog 1
Commits
981d38ed
Commit
981d38ed
authored
Nov 17, 2020
by
Moritz Leibauer
Browse files
implemented Prim
parent
42ae9e27
Changes
1
Show whitespace changes
Inline
Side-by-side
mySpanningTree.java
View file @
981d38ed
...
...
@@ -37,7 +37,60 @@ public class mySpanningTree {
}
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
;
}
...
...
Write
Preview
Supports
Markdown
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment