62 lines
1.2 KiB
C++
62 lines
1.2 KiB
C++
#ifndef BREADTH_FIRST_SEARCH_H_
|
|
#define BREADTH_FIRST_SEARCH_H_
|
|
|
|
#include "graph/digraph.h"
|
|
|
|
#include <queue>
|
|
|
|
using namespace graph;
|
|
|
|
namespace algo {
|
|
|
|
template<typename T>
|
|
class BreadthFirstSearch {
|
|
public:
|
|
BreadthFirstSearch() = default;
|
|
|
|
BreadthFirstSearch(Digraph<T> G) : G(G) {}
|
|
|
|
std::map<T, std::set<T>> execute(const T& root);
|
|
|
|
// Initialize LU table that show which vertices have been traversed
|
|
std::map<T, bool> initExplore();
|
|
private:
|
|
Graph<T> G;
|
|
};
|
|
|
|
template<typename T>
|
|
std::map<T, bool> BreadthFirstSearch<T>::initExplore() {
|
|
std::map<T, bool> graphExplore;
|
|
for (const auto& v : G.adjMatrix) {
|
|
graphExplore[v.first] = false;
|
|
}
|
|
return graphExplore;
|
|
}
|
|
|
|
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> 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 |