Skip to content

Instantly share code, notes, and snippets.

@stevensona
Last active April 21, 2016 11:42
Show Gist options
  • Save stevensona/9d83bc2955d0bcd431390daf07a48f0c to your computer and use it in GitHub Desktop.
Save stevensona/9d83bc2955d0bcd431390daf07a48f0c to your computer and use it in GitHub Desktop.
Simple graph with bidirectional, constant length edges
#pragma once
#include <vector>
#include <list>
#include <queue>
#include <memory>
#include <sstream>
class Graph {
std::vector<std::list<int>> adj;
std::vector<bool> visited;
std::vector<int> parent;
std::vector<int> distance;
public:
Graph(int n) : adj(n), visited(n, false), parent(n, -1), distance(n, 0) {}
void add_edge(int s, int v) {
adj[s].push_back(v);
adj[v].push_back(s);
}
void bfs(int s, std::ostream &out) {
for (size_t n = 0; n < adj.size(); ++n) {
visited[n] = false;
parent[n] = false;
distance[n] = -1;
}
std::queue<int> frontier;
frontier.push(s);
visited[s] = true;
parent[s] = -1;
distance[s] = 0;
while (!frontier.empty()) {
int c = frontier.front();
for (auto n : adj[c]) {
if (!visited[n]) {
frontier.push(n);
visited[n] = true;
parent[n] = c;
distance[n] = distance[c] + 1;
}
}
frontier.pop();
}
for (size_t n = 0; n < adj.size(); ++n) {
if (n == s) {
continue;
}
out << distance[n] << ' ';
}
out << '\n';
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment