GraphLib
Bearbeitung der Aufgabe Mini Graph Library für OOP WiSe 2023/24
Loading...
Searching...
No Matches
kruskal.h
Go to the documentation of this file.
1#ifndef GRAPHLIB_ALGORITHMS_KRUSKAL_H
2#define GRAPHLIB_ALGORITHMS_KRUSKAL_H
3
4#include <algorithm>
5#include <functional>
6#include <map>
7
9
16
17namespace GraphLib {
18
23
36template <Internal::valid_weighted_undirected_graph_type G>
37G kruskal(const G& graph)
38{
39 using id_type = G::id_type;
40 using edge_weight_type = typename G::edge_type::weight_type;
41
42 G mst {};
43
44 for (const auto& id : graph.get_nodes()) {
45 mst.add_node_with_id(id, graph.get_node_data(id));
46 }
47
48 // Jede Node anfänglich eigener Parent, jede Node hat eigenes Set
49 std::map<id_type, id_type> parent;
50 for (const auto& id : graph.get_nodes()) {
51 parent[id] = id;
52 }
53
54 // finde root/Ursprungsnode eines Sets und sorge dafür, dass jede Node direkt auf root zeigt
55 // find_set(a): pfad a->b->c wird zu a->c, b-> c
56 std::function<id_type(id_type)> find_set = [&parent, &find_set](id_type node) {
57 if (parent[node] != node) {
58 parent[node] = find_set(parent[node]);
59 }
60 return parent[node];
61 };
62
63 // Vereinigung zweier Sets, root eines Sets zeigt auf Root anderes Sets
64 auto union_sets = [&find_set, &parent](id_type a, id_type b) { parent[find_set(a)] = find_set(b); };
65
66 // Sammle alle Kanten
67 std::vector<std::tuple<edge_weight_type, id_type, id_type>> edges;
68 for (const auto& id : graph.get_nodes()) {
69 for (const auto& neighbor : graph.get_neighbors(id)) {
70 if (id < neighbor) { // Add each edge only once
71 auto edge = graph.get_edge(id, neighbor);
72 edges.emplace_back(edge.weight, id, neighbor);
73 }
74 }
75 }
76
77 // Sortiere Kanten nach Gewicht
78 std::sort(edges.begin(), edges.end());
79
80 // Arbeite Kanten nach Gewicht ab.
81 for (const auto& [weight, u, v] : edges) {
82 if (find_set(u) != find_set(v)) { // wenn nodes in versch. sets (um zyklenbildung zu vermeiden),
83 mst.add_edge(u, v, weight); // füge kante zu mst hinzu und merge sets
84 union_sets(u, v);
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 kruskal(const G &graph)
Computes the Minimum Spanning Tree of a weighted undirected graph using Kruskal's algorithm.
Definition kruskal.h:37