#ifndef BREADTH_FIRST_SEARCH_H_ #define BREADTH_FIRST_SEARCH_H_ #include #include #include using namespace graph; namespace algo { template class BreadthFirstSearch { public: BreadthFirstSearch() = default; BreadthFirstSearch(std::map> adjMatrix) : adjMatrix(adjMatrix) {} // Traverse whole graph using the BFS search, and save the tree graph // which is created when visiting new vertices (Breadth First Tree) std::map> execute(const T& root); // Search if target vertex exists in graph bool query(const T& root, const T& target); void setGraph(std::map> adjMatrix); private: // Represents the graph on which the algorithm will be executed std::map> adjMatrix; }; template std::map> BreadthFirstSearch::execute(const T& root) { std::map> tree; std::map visited; std::queue Q; Q.push(root); visited[root] = true; while (!Q.empty()) { const auto v = Q.front(); Q.pop(); for (const auto& u : adjMatrix[v]) { if (!visited[u]) { visited[u] = true; tree[v].insert(u); Q.push(u); } } } return tree; } template bool BreadthFirstSearch::query(const T& root, const T& target) { std::map visited; std::queue Q; Q.push(root); visited[root] = true; while (!Q.empty()) { const auto v = Q.front(); Q.pop(); if (v == target) return true; for (const auto& u : adjMatrix[v]) { if (!visited[u]) { visited[u] = true; Q.push(u); } } } return false; } template void BreadthFirstSearch::setGraph(std::map> adjMatrix) { this->adjMatrix = adjMatrix; } } // namespace algo #endif