Files
reachability-algorithms/algorithm/breadth_first_search.h
2022-10-12 16:57:48 +03:00

80 lines
1.6 KiB
C++

#ifndef BREADTH_FIRST_SEARCH_H_
#define BREADTH_FIRST_SEARCH_H_
#include <map>
#include <set>
#include <queue>
using namespace graph;
namespace algo {
template<typename T>
class BreadthFirstSearch {
public:
BreadthFirstSearch() = default;
BreadthFirstSearch(std::map<T, std::set<T>> adjList)
: adjList(adjList) {}
// Traverse whole graph using the BFS search, and save the tree graph
// which is created when visiting new vertices (Breadth First Tree)
std::map<T, std::set<T>> execute(const T& root);
// Search if target vertex exists in graph
bool query(const T& root, const T& target);
private:
// Represents the graph on which the algorithm will be executed
std::map<T, std::set<T>> adjList;
};
template<typename T>
std::map<T, std::set<T>> BreadthFirstSearch<T>::execute(const T& root) {
std::map<T, std::set<T>> tree;
std::map<T, bool> visited;
std::queue<T> Q;
Q.push(root);
visited[root] = true;
while (!Q.empty()) {
const auto v = Q.front();
Q.pop();
for (const auto& u : adjList[v]) {
if (!visited[u]) {
visited[u] = true;
tree[v].insert(u);
tree[u];
Q.push(u);
}
}
}
return tree;
}
template<typename T>
bool BreadthFirstSearch<T>::query(const T& root, const T& target) {
std::map<T, bool> visited;
std::queue<T> Q;
Q.push(root);
visited[root] = true;
while (!Q.empty()) {
const auto v = Q.front();
Q.pop();
if (v == target) return true;
for (const auto& u : adjList[v]) {
if (!visited[u]) {
visited[u] = true;
Q.push(u);
}
}
}
return false;
}
} // namespace algo
#endif