Skip to content

Instantly share code, notes, and snippets.

@JamesBremner
Created August 30, 2023 14:30
Show Gist options
  • Save JamesBremner/71b94a4a2f55da1ea06f8ca633956796 to your computer and use it in GitHub Desktop.
Save JamesBremner/71b94a4a2f55da1ea06f8ca633956796 to your computer and use it in GitHub Desktop.
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
#include "GraphTheory.h"
#include <iostream>
void readDot(std::istringstream &input, raven::graph::sGraphData &gd)
{
gd.g.clear();
gd.g.directed();
std::string a;
while (getline(input, a, ';'))
{
int p = a.find("->");
if (p != -1)
{
gd.g.add(a.substr(0, p),
a.substr(p + 2));
}
}
}
void bfs(
raven::graph::sGraphData &gd)
{
// queue of visited vertices with unsearched children
std::queue<int> Q;
// track nodes that have been visited
// prevent getting caught going around and around a cycle
std::vector<bool> visited(gd.g.vertexCount(), false);
// get vertex indices from user names
int start = gd.g.find(gd.startName);
// start at start
int v = start;
std::cout << gd.g.userName(v) << " ";
Q.push(v);
visited[v] = true;
// loop while the queue is not empty
while (!Q.empty())
{
// get current vertex from front of queue
v = Q.front();
Q.pop();
// loop over vertices reachable from current vertex
for (int u : gd.g.adjacentOut(v))
{
if (!visited[u])
{
// visit to a new node
std::cout << gd.g.userName(u) << " ";
// add to queue and mark visited
Q.push(u);
visited[u] = true;
}
}
}
std::cout << "\n";
}
int main()
{
std::istringstream input(
"digraph{"
"0;1;2;3;4;5;6;7;8;9;"
"0->1;1->2;2->3;2->6;3->4;4->5;5->8;6->7;6->5;7->8;8->9;"
"}");
const std::string start_index = "6";
raven::graph::sGraphData gd;
gd.startName = "6";
readDot(input, gd);
bfs(gd);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment