Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions examples/bfsExample.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
#include <iostream>
#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<Vertex, double, Appledore::UndirectedG> 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<Vertex, double> dist = undirected.bfs(v1, 10);

for (Vertex v : undirected.getVertices()) {
std::cout << dist[v] << std::endl;
}

std::cout << "\n";
return 0;
}
35 changes: 35 additions & 0 deletions include/GraphMatrix.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,10 @@
#include <stack>
#include <algorithm>
#include <set>
#include <queue>
#include <limits>
#include "MatrixRep.hpp"

namespace Appledore
{

Expand Down Expand Up @@ -518,6 +521,38 @@ namespace Appledore
}
}

std::map<VertexType, EdgeType> bfs(VertexType& startVertex, size_t maxDepth) {
size_t start = vertexToIndex[startVertex];
EdgeType inf = std::numeric_limits<EdgeType>::infinity();
std::map<VertexType, EdgeType> dist;

for (size_t i = 0; i < numVertices; i++) {
dist[indexToVertex[i]] = inf;
}

dist[startVertex] = 0;

std::queue<VertexType> 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()
// ---------------------------------------------------------
Expand Down
5 changes: 5 additions & 0 deletions include/MatrixRep.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down