Files
reachability-algorithms/algorithm/bfs.h
2022-06-11 19:27:03 +03:00

62 lines
1.0 KiB
C++

#ifndef BFS_H_
#define BFS_H_
#include "graph/graph.h"
using namespace graph;
#include <algorithm>
#include <queue>
namespace algo {
template<typename T>
class BFS {
public:
BFS(Graph<T> G, T root) : G(G), root(root) {}
//
std::map<T, std::set<T>> run();
//
std::map<T, bool> initExplore();
private:
Graph<T> G;
T root;
};
template<typename T>
std::map<T, bool> BFS<T>::initExplore() {
std::map<T, bool> graphExplore;
for (const auto& v : G.vertices) {
graphExplore[v] = false;
}
return graphExplore;
}
template<typename T>
std::map<T, std::set<T>> BFS<T>::run() {
std::map<T, std::set<T>> tree;
std::map<T, bool> graphExplore = initExplore();
std::queue<T> Q;
Q.push(root);
graphExplore[root] = true;
while (!Q.empty()) {
const auto v = Q.front();
Q.pop();
for (const auto& u : G.adjMatrix[v]) {
if (!graphExplore[u]) {
graphExplore[u] = true;
tree[v].insert(u);
Q.push(u);
}
}
}
return tree;
}
} // namespace algo
#endif