GraphLib
Bearbeitung der Aufgabe Mini Graph Library für OOP WiSe 2023/24
Loading...
Searching...
No Matches
bfs.h
Go to the documentation of this file.
1#ifndef GRAPHLIB_ALGORITHMS_BFS_H
2#define GRAPHLIB_ALGORITHMS_BFS_H
3
4#include <queue>
5#include <set>
6#include <vector>
7
9
20
21namespace GraphLib {
22
31
47template <Internal::valid_graph_type G>
48std::vector<typename G::id_type> breadth_first_search(const G& graph, typename G::id_type root,
49 typename G::id_type target)
50{
51 using id_type = G::id_type;
52
53 if (!graph.node_exists(root)) {
54 throw std::runtime_error("Root ID does not exist in Graph, cannot conduct BFS");
55 } else if (!graph.node_exists(target)) {
56 throw std::runtime_error("Target ID does not exist in Graph, cannot conduct BFS");
57 }
58
59 // speichere node und path zur node in queue
60 std::queue<std::pair<id_type, std::vector<id_type>>> queue {{{root, {root}}}};
61
62 std::set<id_type> seen {root};
63 std::vector<id_type> path {};
64
65 while (!queue.empty()) {
66 auto [current_node, path_so_far] = queue.front();
67 queue.pop();
68
69 if (current_node == target)
70 return path_so_far;
71
72 for (id_type neighbor : graph.get_neighbors(current_node)) {
73 if (!seen.contains(neighbor)) {
74 auto new_path = path_so_far;
75 new_path.push_back(neighbor);
76 queue.push({neighbor, new_path});
77 }
78 seen.insert(neighbor);
79 }
80 }
81 return std::vector<id_type> {};
82}
83
97template <Internal::valid_graph_type G>
98G breadth_first_search(const G& graph, typename G::id_type root)
99{
100 using id_type = G::id_type;
101
102 if (!graph.node_exists(root)) {
103 throw std::runtime_error("Root ID does not exist in Graph, cannot construct Spanning Tree");
104 }
105
106 G mst {};
107 std::set<id_type> seen {root};
108 std::queue<id_type> queue({root});
109
110 for (const auto& id : graph.get_nodes()) {
111 mst.add_node_with_id(id, graph.get_node_data(id));
112 }
113
114 while (!queue.empty()) {
115 id_type current = queue.front();
116 queue.pop();
117
118 for (id_type neighbor : graph.get_neighbors(current)) {
119 if (!seen.contains(neighbor)) {
121 mst.add_edge(current, neighbor, graph.get_edge_weight(current, neighbor));
122 } else {
123 mst.add_edge(current, neighbor);
124 }
125 seen.insert(neighbor);
126 queue.push(neighbor);
127 }
128 }
129 }
130
131 return mst;
132}
133
135} // namespace GraphLib
136
137#endif
Checks if a type derives from WeightedGraph.
Definition concepts.h:179
Defines C++20 concepts used for type constraints in the GraphLib library.
std::vector< typename G::id_type > breadth_first_search(const G &graph, typename G::id_type root, typename G::id_type target)
Performs a breadth-first search (BFS) to find a path from root to target node in a graph.
Definition bfs.h:48