diff --git a/examples/bfsExample.cpp b/examples/bfsExample.cpp new file mode 100755 index 0000000..444b634 --- /dev/null +++ b/examples/bfsExample.cpp @@ -0,0 +1,38 @@ +#include +#include "../include/GraphMatrix.hpp" + +class Vertex : public Appledore::GraphVertex { + public: + int data; + Vertex(int d): data(d) {}; +}; + +int main() { + + // In order to use bfs, EdgeType must support the operator+ and must have + // infinity. + Appledore::GraphMatrix undirected; + + Vertex v1(4); + Vertex v2(10); + Vertex v3(12); + Vertex v4(2); + + undirected.addVertex(v1); + undirected.addVertex(v2); + undirected.addVertex(v3); + undirected.addVertex(v4); + + undirected.addEdge(v1,v2,1); + undirected.addEdge(v2,v3,1); + undirected.addEdge(v1,v4,1); + + std::map dist = undirected.bfs(v1, 10); + + for (Vertex v : undirected.getVertices()) { + std::cout << dist[v] << std::endl; + } + + std::cout << "\n"; + return 0; +} \ No newline at end of file diff --git a/include/GraphMatrix.hpp b/include/GraphMatrix.hpp index cd2eea2..e14e555 100644 --- a/include/GraphMatrix.hpp +++ b/include/GraphMatrix.hpp @@ -8,7 +8,10 @@ #include #include #include +#include +#include #include "MatrixRep.hpp" + namespace Appledore { @@ -518,6 +521,38 @@ namespace Appledore } } + std::map bfs(VertexType& startVertex, size_t maxDepth) { + size_t start = vertexToIndex[startVertex]; + EdgeType inf = std::numeric_limits::infinity(); + std::map dist; + + for (size_t i = 0; i < numVertices; i++) { + dist[indexToVertex[i]] = inf; + } + + dist[startVertex] = 0; + + std::queue queue; + queue.push(indexToVertex[start]); + size_t depth = 0; + + while (!queue.empty() && depth <= maxDepth) { + VertexType current = queue.front(); + queue.pop(); + depth = dist[current]; + + for (VertexType neighbor : getNeighbors(current)) { + EdgeType weight = getEdge(current, neighbor); + + if (dist[neighbor] == inf) { + dist[neighbor] = dist[current] + weight; + queue.push(neighbor); + } + } + } + return dist; + }; + // --------------------------------------------------------- // NEW METHOD: removeVertex() // --------------------------------------------------------- diff --git a/include/MatrixRep.hpp b/include/MatrixRep.hpp index 83c2bf2..c310e52 100644 --- a/include/MatrixRep.hpp +++ b/include/MatrixRep.hpp @@ -39,6 +39,11 @@ namespace Appledore { return id == other.id; } + + friend std::ostream& operator<<(std::ostream& src, const GraphVertex& other) { + src << "Vertex " << other.id; + return src; + } }; size_t Appledore::GraphVertex::nextId = 1; class GraphEdge