62 lines
1.1 KiB
C++
62 lines
1.1 KiB
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(Graph<T> G) : G(G) {}
|
|
|
|
//
|
|
Digraph<T> run(const T& root);
|
|
|
|
// Initialize the lookup table that is used to
|
|
// show which vertices have been traversed
|
|
std::map<T, bool> initExplore();
|
|
private:
|
|
Graph<T> G;
|
|
};
|
|
|
|
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>
|
|
Digraph<T> BFS<T>::run(const T& root) {
|
|
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 Digraph<T>(tree);
|
|
}
|
|
|
|
} // namespace algo
|
|
|
|
#endif |