Update object graph implementation to track node discover and finish time

+ Allows traversal and topological sort algorithms to show examples from MIT Algorithms more accurately
This commit is contained in:
Shaun Reed 2021-06-28 12:46:04 -04:00
parent 5d37db1ce2
commit 348586ec38
4 changed files with 58 additions and 75 deletions

View File

@ -16,3 +16,4 @@ project (
) )
add_subdirectory(simple) add_subdirectory(simple)
add_subdirectory(object)

View File

@ -14,7 +14,7 @@
int main (const int argc, const char * argv[]) int main (const int argc, const char * argv[])
{ {
// We could initialize the graph with some localNodes... // We could initialize the graph with some localNodes...
std::map<int, std::set<int>> localNodes{ std::map<int, std::vector<int>> localNodes{
{1, {2, 5}}, // Node 1 {1, {2, 5}}, // Node 1
{2, {1, 6}}, // Node 2 {2, {1, 6}}, // Node 2
{3, {4, 6, 7}}, {3, {4, 6, 7}},
@ -26,13 +26,6 @@ int main (const int argc, const char * argv[])
}; };
// Graph bfsGraph(localNodes); // Graph bfsGraph(localNodes);
// Graph testGraph(
// {
// {Node(1, {2, 5})},
//// {Node(1, {2, 5})},
// }
// )
std::cout << "\n\n##### Breadth First Search #####\n"; std::cout << "\n\n##### Breadth First Search #####\n";
// Or we could use an initializer list... // Or we could use an initializer list...
@ -77,19 +70,20 @@ int main (const int argc, const char * argv[])
// Initialize an example graph for Depth First Search // Initialize an example graph for Depth First Search
Graph topologicalGraph ( Graph topologicalGraph (
{ {
{1, {4, 5}}, {6, {8, 7}}, // shirt
{2, {5}}, {8, {9}}, // tie
{3, {}}, {7, {9}}, // belt
{4, {5, 7}}, {9, {}}, // jacket
{5, {}}, {3, {}}, // watch
{6, {7, 8}}, {1, {4, 5}}, // undershorts
{7, {9}}, {4, {5, 7}}, // pants
{8, {9}}, {5, {}}, // shoes
{9, {}}, {2, {5}}, // socks
} }
); );
// The graph traversed in this example is seen in MIT Intro to Algorithms // The graph traversed in this example is seen in MIT Intro to Algorithms
// + Chapter 22, Figure 22.4 on DFS // + Chapter 22, Figure 22.4 on DFS
// Unlike the simple-graph example, this final result matches MIT Algorithms
std::vector<Node> order = topologicalGraph.TopologicalSort(); std::vector<Node> order = topologicalGraph.TopologicalSort();
std::cout << "\n\nTopological order: "; std::cout << "\n\nTopological order: ";
while (!order.empty()) { while (!order.empty()) {

View File

@ -52,6 +52,7 @@ void Graph::DFS() const
{ {
// Track the nodes we have discovered // Track the nodes we have discovered
for (const auto &node : nodes_) node.color = White; for (const auto &node : nodes_) node.color = White;
int time = 0;
// Visit each node in the graph // Visit each node in the graph
for (const auto& node : nodes_) { for (const auto& node : nodes_) {
@ -60,69 +61,43 @@ void Graph::DFS() const
if (node.color == White) { if (node.color == White) {
std::cout << "Found undiscovered node: " << node.number << std::endl; std::cout << "Found undiscovered node: " << node.number << std::endl;
// Visiting the undiscovered node will check it's adjacent nodes // Visiting the undiscovered node will check it's adjacent nodes
DFSVisit(node); DFSVisit(time, node);
} }
} }
} }
void Graph::DFSVisit(const Node& startNode) const void Graph::DFSVisit(int &time, const Node& startNode) const
{ {
startNode.color = Gray; startNode.color = Gray;
time++;
startNode.discoveryFinish.first = time;
// Check the adjacent nodes of the startNode // Check the adjacent nodes of the startNode
for (const auto &adjacent : startNode.adjacent) { for (const auto &adjacent : startNode.adjacent) {
auto iter = std::find(nodes_.begin(), nodes_.end(),
Node(adjacent, {}));
// If the adjacentNode is undiscovered, visit it // If the adjacentNode is undiscovered, visit it
// + Offset by 1 to account for 0 index of discovered vector // + Offset by 1 to account for 0 index of discovered vector
if (nodes_[adjacent - 1].color == White) { if (iter->color == White) {
std::cout << "Found undiscovered adjacentNode: " std::cout << "Found undiscovered adjacentNode: "
<< nodes_[adjacent - 1].number << std::endl; << nodes_[adjacent - 1].number << std::endl;
// Visiting the undiscovered node will check it's adjacent nodes // Visiting the undiscovered node will check it's adjacent nodes
DFSVisit(nodes_[adjacent - 1]); DFSVisit(time, *iter);
} }
} }
startNode.color = Black; startNode.color = Black;
time++;
startNode.discoveryFinish.second = time;
} }
std::vector<Node> Graph::TopologicalSort() const std::vector<Node> Graph::TopologicalSort() const
{ {
std::vector<Node> topologicalOrder; DFS();
std::vector<Node> topological(nodes_);
// Track the nodes we have discovered std::sort(topological.begin(), topological.end(), Node::FinishedSort);
for (const auto &node : nodes_) node.color = White;
// Visit each node in the graph
for (const auto &node : nodes_) {
std::cout << "Visiting node " << node.number << std::endl;
// If the node is undiscovered, visit it
if (node.color == White) {
std::cout << "Found undiscovered node: " << node.number << std::endl;
// Visiting the undiscovered node will check it's adjacent nodes
TopologicalVisit(node, topologicalOrder);
}
}
// The topologicalOrder is read right-to-left in the final result // The topologicalOrder is read right-to-left in the final result
// + Output is handled in main as FILO, similar to a stack // + Output is handled in main as FILO, similar to a stack
return topologicalOrder; return topological;
}
void Graph::TopologicalVisit(const Node &startNode,
std::vector<Node> &order) const
{
// Mark the node as visited so we don't visit it twice
startNode.color = Gray;
// Check the adjacent nodes of the startNode
for (const auto& adjacent : startNode.adjacent) {
// If the adjacentNode is undiscovered, visit it
if (nodes_[adjacent - 1].color == White) {
std::cout << "Found undiscovered adjacentNode: " << adjacent << std::endl;
// Visiting the undiscovered node will check it's adjacent nodes
TopologicalVisit(nodes_[adjacent - 1], order);
}
}
startNode.color = Black;
// Add startNode to the topologicalOrder
order.push_back(startNode);
} }

View File

@ -13,33 +13,48 @@
#include <iostream> #include <iostream>
#include <algorithm> #include <algorithm>
#include <map> #include <map>
#include <set>
#include <utility> #include <utility>
#include <vector> #include <vector>
#include <queue> #include <queue>
#include <unordered_set>
// A vertex can also be referred to as a node
// + ... Unless you are a mathematician ^.^
struct Vertex {
// This vertex's number
int number;
// A set of all vertices adjacent to this vertex
std::set<int> adjacent;
};
enum Color {White, Gray, Black}; enum Color {White, Gray, Black};
struct Node { struct Node {
public: public:
Node(int num, std::set<int> adj) : number(num), adjacent(std::move(adj)) {} Node(const Node &rhs) = default;
Node & operator=(Node rhs) {
if (this == &rhs) return *this;
swap(*this, rhs);
return *this;
}
friend void swap(Node &a, Node &b) {
std::swap(a.number, b.number);
std::swap(a.adjacent, b.adjacent);
std::swap(a.color, b.color);
std::swap(a.discoveryFinish, b.discoveryFinish);
}
Node(int num, std::vector<int> adj) :
number(num), adjacent(std::move(adj)) {}
int number; int number;
std::set<int> adjacent; std::vector<int> adjacent;
// Mutable so we can update the color of the nodes during traversal // Mutable so we can update the color of the nodes during traversal
mutable Color color = White; mutable Color color = White;
std::vector<int> predecessors; // Create a pair to track discovery / finish time
// + Discovery time is the iteration the node is first discovered
// + Finish time is the iteration the node has been checked completely
// ++ A finished node has considered all adjacent nodes
mutable std::pair<int, int> discoveryFinish;
// bool operator<(const Node &node1) const { return number < node1.number;} // Define a comparator for std::sort
inline void setColor(Color newColor) const { color = newColor;} // + This will help to sort nodes by finished time after traversal
static bool FinishedSort(const Node &node1, const Node &node2)
{ return node1.discoveryFinish.second < node2.discoveryFinish.second;}
// Define operator== for std::find
bool operator==(const Node &b) const { return this->number == b.number;}
}; };
class Graph { class Graph {
@ -49,10 +64,8 @@ public:
void BFS(const Node& startNode) const; void BFS(const Node& startNode) const;
void DFS() const; void DFS() const;
void DFSVisit(const Node& startNode) const; void DFSVisit(int &time, const Node& startNode) const;
std::vector<Node> TopologicalSort() const; std::vector<Node> TopologicalSort() const;
void TopologicalVisit(const Node &startNode, std::vector<Node> &order) const;
}; };
#endif // LIB_GRAPH_HPP #endif // LIB_GRAPH_HPP