Files
reachability-algorithms/algorithm/bfs.h

62 lines
1016 B
C++

#ifndef BFS_H_
#define BFS_H_
#include "graph/digraph.h"
#include <queue>
using namespace graph;
namespace algo {
template<typename T>
class BFS {
public:
BFS(Digraph<T> G, T root) : G(G), root(root) {}
//
std::map<T, std::set<T>> run();
//
std::map<T, bool> initExplore();
private:
Digraph<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