GraphLib
Bearbeitung der Aufgabe Mini Graph Library für OOP WiSe 2023/24
Loading...
Searching...
No Matches
prim.h
Go to the documentation of this file.
1#ifndef GRAPHLIB_ALGORITHMS_PRIM_H
2#define GRAPHLIB_ALGORITHMS_PRIM_H
3
4#include <set>
5
7
15
16namespace GraphLib {
17
22
36template <Internal::valid_weighted_undirected_graph_type G>
37G prim(const G& graph, typename G::id_type root)
38{
39 using id_type = G::id_type;
40 using edge_type = G::edge_type;
41 using edge_weight_type = typename G::edge_type::weight_type;
42
43 if (!graph.node_exists(root)) {
44 throw std::runtime_error("Root ID does not exist in Graph, cannot conduct Prim Algorithm");
45 }
46
47 G mst {};
48
49 for (const auto& id : graph.get_nodes()) {
50 mst.add_node_with_id(id, graph.get_node_data(id));
51 }
52
53 std::set<id_type> visited {root};
54
55 while (visited.size() < graph.get_nodes().size()) {
56 edge_type min_edge {{0}, edge_weight_type {}};
57 id_type from_node;
58 id_type to_node;
59 bool found_edge = false;
60
61 // schaue durch besuchte Knoten
62 for (id_type current : visited) {
63 // Prüfe alle ihre Nachbarn
64 for (id_type neighbor : graph.get_neighbors(current)) {
65 if (visited.contains(neighbor)) {
66 continue;
67 }
68
69 auto current_edge = graph.get_edge(current, neighbor);
70 // Falls erste gefundene Kante oder Gewicht kleiner als bisheriges Minimum
71 if (!found_edge || current_edge.weight < min_edge.weight) {
72 min_edge = current_edge;
73 from_node = current;
74 to_node = neighbor;
75 found_edge = true;
76 }
77 }
78 }
79
80 if (found_edge) {
81 mst.add_edge(from_node, to_node, min_edge.weight);
82 visited.insert(to_node);
83 } else {
84 throw std::runtime_error("Graph is not connected - cannot construct minimum spanning tree");
85 }
86 }
87
88 return mst;
89}
90
91} // namespace GraphLib
92
93#endif
Defines C++20 concepts used for type constraints in the GraphLib library.
G prim(const G &graph, typename G::id_type root)
Computes the Minimum Spanning Tree of a weighted undirected graph using Prim's algorithm.
Definition prim.h:37