Add BFS tree
This commit is contained in:
62
algorithm/bfs.h
Normal file
62
algorithm/bfs.h
Normal file
@@ -0,0 +1,62 @@
|
||||
#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
|
||||
Reference in New Issue
Block a user