37G
prim(
const G& graph,
typename G::id_type root)
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;
43 if (!graph.node_exists(root)) {
44 throw std::runtime_error(
"Root ID does not exist in Graph, cannot conduct Prim Algorithm");
49 for (
const auto&
id : graph.get_nodes()) {
50 mst.add_node_with_id(
id, graph.get_node_data(
id));
53 std::set<id_type> visited {root};
55 while (visited.size() < graph.get_nodes().size()) {
56 edge_type min_edge {{0}, edge_weight_type {}};
59 bool found_edge =
false;
62 for (id_type current : visited) {
64 for (id_type neighbor : graph.get_neighbors(current)) {
65 if (visited.contains(neighbor)) {
69 auto current_edge = graph.get_edge(current, neighbor);
71 if (!found_edge || current_edge.weight < min_edge.weight) {
72 min_edge = current_edge;
81 mst.add_edge(from_node, to_node, min_edge.weight);
82 visited.insert(to_node);
84 throw std::runtime_error(
"Graph is not connected - cannot construct minimum spanning tree");