From 835dbc7f7dba46e4a5d5ebcfc6ed6fdb6db884f2 Mon Sep 17 00:00:00 2001 From: Shaun Reed Date: Fri, 16 Jul 2021 12:28:41 -0400 Subject: [PATCH] Initial commit for working on weighted-graph implementation --- cpp/algorithms/graphs/weighted/CMakeLists.txt | 22 ++ cpp/algorithms/graphs/weighted/graph.cpp | 140 +++++++++++++ cpp/algorithms/graphs/weighted/lib-graph.cpp | 189 ++++++++++++++++++ cpp/algorithms/graphs/weighted/lib-graph.hpp | 134 +++++++++++++ 4 files changed, 485 insertions(+) create mode 100644 cpp/algorithms/graphs/weighted/CMakeLists.txt create mode 100644 cpp/algorithms/graphs/weighted/graph.cpp create mode 100644 cpp/algorithms/graphs/weighted/lib-graph.cpp create mode 100644 cpp/algorithms/graphs/weighted/lib-graph.hpp diff --git a/cpp/algorithms/graphs/weighted/CMakeLists.txt b/cpp/algorithms/graphs/weighted/CMakeLists.txt new file mode 100644 index 0000000..f99e265 --- /dev/null +++ b/cpp/algorithms/graphs/weighted/CMakeLists.txt @@ -0,0 +1,22 @@ +################################################################################ +## Author: Shaun Reed ## +## Legal: All Content (c) 2021 Shaun Reed, all rights reserved ## +## About: A basic CMakeLists configuration to test RBT implementation ## +## ## +## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ## +################################################################################ +# + +cmake_minimum_required(VERSION 3.15) + +project( + #[[NAME]] WeightedGraph + VERSION 1.0 + DESCRIPTION "Practice implementing and using weighted graphs in C++" + LANGUAGES CXX +) + +add_library(lib-graph-weighted "lib-graph.cpp") + +add_executable(graph-test-weighted "graph.cpp") +target_link_libraries(graph-test-weighted lib-graph-weighted) diff --git a/cpp/algorithms/graphs/weighted/graph.cpp b/cpp/algorithms/graphs/weighted/graph.cpp new file mode 100644 index 0000000..990db59 --- /dev/null +++ b/cpp/algorithms/graphs/weighted/graph.cpp @@ -0,0 +1,140 @@ +/*############################################################################## +## Author: Shaun Reed ## +## Legal: All Content (c) 2021 Shaun Reed, all rights reserved ## +## About: An example of an object graph implementation ## +## Algorithms in this example are found in MIT Intro to Algorithms ## +## ## +## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ## +################################################################################ +*/ + +#include "lib-graph.hpp" + + +int main (const int argc, const char * argv[]) +{ + // We could initialize the graph with some localNodes... + std::vector localNodes{ + {1, {2, 5}}, // Node 1 + {2, {1, 6}}, // Node 2 + {3, {4, 6, 7}}, + {4, {3, 7, 8}}, + {5, {1}}, + {6, {2, 3, 7}}, + {7, {3, 4, 6, 8}}, + {8, {4, 6}}, + }; + Graph bfsGraphInit(localNodes); + + + std::cout << "\n\n##### Breadth First Search #####\n"; + // Or we could use an initializer list... + // Initialize a example graph for Breadth First Search + Graph bfsGraph( + { + {1, {2, 5}}, // Node 1 + {2, {1, 6}}, // Node 2... + {3, {4, 6, 7}}, + {4, {3, 7, 8}}, + {5, {1}}, + {6, {2, 3, 7}}, + {7, {3, 4, 6, 8}}, + {8, {4, 6}}, + } + ); + // The graph traversed in this example is seen in MIT Intro to Algorithms + // + Chapter 22, Figure 22.3 on BFS + bfsGraph.BFS(bfsGraph.GetNodeCopy(2)); + + std::cout << "\nTesting finding a path between two nodes using BFS...\n"; + // Test finding a path between two nodes using BFS + auto path = bfsGraph.PathBFS( + bfsGraph.GetNodeCopy(1), bfsGraph.GetNodeCopy(7) + ); + // If we were returned an empty path, it doesn't exist + if (path.empty()) std::cout << "No valid path found!\n"; + else { + // If we were returned a path, print it + std::cout << "\nValid path from " << path.front().number + << " to " << path.back().number << ": "; + for (const auto &node : path) { + std::cout << node.number << " "; + } + std::cout << std::endl; + } + + + std::cout << "\n\n##### Depth First Search #####\n"; + // Initialize an example graph for Depth First Search + Graph dfsGraph( + { + {1, {2, 4}}, + {2, {5}}, + {3, {5, 6}}, + {4, {2}}, + {5, {4}}, + {6, {6}}, + } + ); + // The graph traversed in this example is seen in MIT Intro to Algorithms + // + Chapter 22, Figure 22.4 on DFS + dfsGraph.DFS(); + + + std::cout << "\n\n##### Topological Sort #####\n"; + // Initialize an example graph for Depth First Search + // + The order of initialization is important + // + To produce the same result as seen in the book + // ++ If the order is changed, other valid topological orders will be found + // The book starts on the 'shirt' node (with the number 6, in this example) + Graph topologicalGraph ( + { + {1, {4, 5}}, // undershorts + {2, {5}}, // socks + {3, {}}, // watch + {4, {5, 7}}, // pants + {5, {}}, // shoes + {6, {8, 7}}, // shirt + {7, {9}}, // belt + {8, {9}}, // tie + {9, {}}, // jacket + } + ); + + // The graph traversed in this example is seen in MIT Intro to Algorithms + // + Chapter 22, Figure 22.4 on DFS + // Unlike the simple-graph example, this final result matches MIT Algorithms + // + Aside from the placement of the watch node, which is not connected + // + This is because the node is visited after all other nodes are finished + std::vector order = + topologicalGraph.TopologicalSort(topologicalGraph.GetNodeCopy(6)); + std::cout << "\nTopological order: "; + while (!order.empty()) { + std::cout << order.back().number << " "; + order.pop_back(); + } + std::cout << std::endl << std::endl; + + // If we want the topological order to match what is seen in the book + // + We have to initialize the graph carefully to get this result - + Graph topologicalGraph2 ( + { + {6, {8, 7}}, // shirt + {8, {9}}, // tie + {7, {9}}, // belt + {9, {}}, // jacket + {3, {}}, // watch + {1, {4, 5}}, // undershorts + {4, {5, 7}}, // pants + {5, {}}, // shoes + {2, {5}}, // socks + } + ); + auto order2 = topologicalGraph2.TopologicalSort(*topologicalGraph2.NodeBegin()); + std::cout << "\nTopological order: "; + while (!order2.empty()) { + std::cout << order2.back().number << " "; + order2.pop_back(); + } + std::cout << std::endl; +} diff --git a/cpp/algorithms/graphs/weighted/lib-graph.cpp b/cpp/algorithms/graphs/weighted/lib-graph.cpp new file mode 100644 index 0000000..c9b019d --- /dev/null +++ b/cpp/algorithms/graphs/weighted/lib-graph.cpp @@ -0,0 +1,189 @@ +/*############################################################################## +## Author: Shaun Reed ## +## Legal: All Content (c) 2021 Shaun Reed, all rights reserved ## +## About: Driver program to test object graph implementation ## +## ## +## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ## +################################################################################ +*/ + +#include "lib-graph.hpp" + + +InfoBFS Graph::BFS(const Node& startNode) const +{ + // Create local object to track the information gathered during traversal + InfoBFS searchInfo; + + // Create a queue to visit discovered nodes in FIFO order + std::queue visitQueue; + + // Mark the startNode as in progress until we finish checking adjacent nodes + searchInfo[startNode.number].discovered = Gray; + + // Visit the startNode + visitQueue.push(&startNode); + + // Continue to visit nodes until there are none left in the graph + while (!visitQueue.empty()) { + // Remove thisNode from the visitQueue, storing its vertex locally + const Node * thisNode = visitQueue.front(); + visitQueue.pop(); + std::cout << "Visiting node " << thisNode->number << std::endl; + + // Check if we have already discovered all the adjacentNodes to thisNode + for (const auto &adjacent : thisNode->adjacent) { + if (searchInfo[adjacent.GetNumber()].discovered == White) { + std::cout << "Found undiscovered adjacentNode: " << adjacent.GetNumber() + << "\n"; + // Mark the adjacent node as in progress + searchInfo[adjacent.GetNumber()].discovered = Gray; + searchInfo[adjacent.GetNumber()].distance = + searchInfo[thisNode->number].distance + 1; + searchInfo[adjacent.GetNumber()].predecessor = + &GetNode(thisNode->number); + + // Add the discovered node the the visitQueue + visitQueue.push(&GetNode(adjacent.GetNumber())); + } + } + // We are finished with this node and the adjacent nodes; Mark it discovered + searchInfo[thisNode->number].discovered = Black; + } + + // Return the information gathered from this search, JIC caller needs it + return searchInfo; +} + +std::deque Graph::PathBFS(const Node &start, const Node &finish) const +{ + // Store the path as copies of each node + // + If the caller modifies these, it will not impact the graph's data + std::deque path; + + InfoBFS searchInfo = BFS(start); + const Node * next = searchInfo[finish.number].predecessor; + bool isValid = false; + do { + // If we have reached the start node, we have found a valid path + if (*next == Node(start)) isValid = true; + + // Add the node to the path as we check each node + // + Use emplace_front to call the Node copy constructor + path.emplace_front(*next); + + // Move to the next node + next = searchInfo[next->number].predecessor; + } while (next != nullptr); + // Use emplace_back to call Node copy constructor + path.emplace_back(finish); + + // If we never found a valid path, erase all contents of the path + if (!isValid) path.erase(path.begin(), path.end()); + + // Return the path, the caller should handle empty paths accordingly + return path; +} + +InfoDFS Graph::DFS() const +{ + // Track the nodes we have discovered + InfoDFS searchInfo; + int time = 0; + + // 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 (searchInfo[node.number].discovered == White) { + std::cout << "Found undiscovered node: " << node.number << std::endl; + // Visiting the undiscovered node will check it's adjacent nodes + DFSVisit(time, node, searchInfo); + } + } + + return searchInfo; +} + +InfoDFS Graph::DFS(const Node &startNode) const +{ + // Track the nodes we have discovered + InfoDFS searchInfo; + int time = 0; + + auto startIter = std::find(nodes_.begin(), nodes_.end(), + Node(startNode.number, {}) + ); + + // beginning at startNode, visit each node in the graph until we reach the end + while (startIter != nodes_.end()) { + std::cout << "Visiting node " << startIter->number << std::endl; + // If the startIter is undiscovered, visit it + if (searchInfo[startIter->number].discovered == White) { + std::cout << "Found undiscovered node: " << startIter->number << std::endl; + // Visiting the undiscovered node will check it's adjacent nodes + DFSVisit(time, *startIter, searchInfo); + } + startIter++; + } + + // Once we reach the last node, check the beginning for unchecked nodes + startIter = nodes_.begin(); + + // Once we reach the initial startNode, we have checked all nodes + while (*startIter != startNode) { + std::cout << "Visiting node " << startIter->number << std::endl; + // If the startIter is undiscovered, visit it + if (searchInfo[startIter->number].discovered == White) { + std::cout << "Found undiscovered node: " << startIter->number << std::endl; + // Visiting the undiscovered node will check it's adjacent nodes + DFSVisit(time, *startIter, searchInfo); + } + startIter++; + } + + return searchInfo; +} + +void Graph::DFSVisit(int &time, const Node& startNode, InfoDFS &searchInfo) const +{ + searchInfo[startNode.number].discovered = Gray; + time++; + searchInfo[startNode.number].discoveryFinish.first = time; + + // Check the adjacent nodes of the startNode + for (const auto &adjacent : startNode.adjacent) { + auto iter = std::find(nodes_.begin(), nodes_.end(), + Node(adjacent.GetNumber(), {})); + // If the adjacentNode is undiscovered, visit it + // + Offset by 1 to account for 0 index of discovered vector + if (searchInfo[iter->number].discovered == White) { + std::cout << "Found undiscovered adjacentNode: " + << GetNode(adjacent.GetNumber()).number << std::endl; + // Visiting the undiscovered node will check it's adjacent nodes + DFSVisit(time, *iter, searchInfo); + } + } + searchInfo[startNode.number].discovered = Black; + time++; + searchInfo[startNode.number].discoveryFinish.second = time; +} + +std::vector Graph::TopologicalSort(const Node &startNode) const +{ + InfoDFS topological = DFS(GetNode(startNode.number)); + + std::vector order(nodes_); + + auto comp = [&topological](const Node &a, const Node &b) { + return (topological[a.number].discoveryFinish.second < + topological[b.number].discoveryFinish.second); + }; + + std::sort(order.begin(), order.end(), comp); + + // The topologicalOrder is read right-to-left in the final result + // + Output is handled in main as FILO, similar to a stack + return order; +} + diff --git a/cpp/algorithms/graphs/weighted/lib-graph.hpp b/cpp/algorithms/graphs/weighted/lib-graph.hpp new file mode 100644 index 0000000..e7c2a54 --- /dev/null +++ b/cpp/algorithms/graphs/weighted/lib-graph.hpp @@ -0,0 +1,134 @@ +/*############################################################################## +## Author: Shaun Reed ## +## Legal: All Content (c) 2021 Shaun Reed, all rights reserved ## +## About: An example of an object graph implementation ## +## Algorithms in this example are found in MIT Intro to Algorithms ## +## ## +## Contact: shaunrd0@gmail.com | URL: www.shaunreed.com | GitHub: shaunrd0 ## +################################################################################ +*/ +#ifndef LIB_GRAPH_HPP +#define LIB_GRAPH_HPP + +#include +#include +#include +#include +#include +#include +#include +#include + + +/******************************************************************************/ +// Structures for tracking information gathered from various traversals +struct Node; +// Color represents the discovery status of any given node +// + White is undiscovered, Gray is in progress, Black is fully discovered +enum Color {White, Gray, Black}; + +// Information used in all searches +struct SearchInfo { + // Coloring of the nodes is used in both DFS and BFS + Color discovered = White; +}; + +// Information that is only used in BFS +struct BFS : SearchInfo { + // Used to represent distance from start node + int distance = 0; + // Used to represent the parent node that discovered this node + // + If we use this node as the starting point, this will remain a nullptr + const Node *predecessor = nullptr; +}; + +// Information that is only used in DFS +struct DFS : SearchInfo { + // 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 + std::pair discoveryFinish; +}; + +// Store search information in unordered_maps so we can pass it around easily +// + Allows each node to store relative information on the traversal +using InfoBFS = std::unordered_map; +using InfoDFS = std::unordered_map; + + +/******************************************************************************/ +// Node structure for representing a graph +struct Link; + +struct Node { +public: + // Constructors + Node(const Node &rhs) = default; + Node & operator=(Node rhs) { + if (this == &rhs) return *this; + swap(*this, rhs); + return *this; + } + Node(int num, std::vector adj) : number(num), adjacent(std::move(adj)) {} + + friend void swap(Node &a, Node &b) { + std::swap(a.number, b.number); + std::swap(a.adjacent, b.adjacent); + } + + int number; + std::vector adjacent; + + // Define operator== for std::find; And comparisons between nodes + bool operator==(const Node &b) const { return this->number == b.number;} + // Define an operator!= for comparing nodes for inequality + bool operator!=(const Node &b) const { return this->number != b.number;} +}; + +struct Link { + explicit Link(Node *n, int w=0) : node(n), weight(w) {} + + Node *node; + int weight; + inline int GetNumber() const { return node->number;} +}; + +/******************************************************************************/ +// Graph class declaration +class Graph { +public: + // Constructor + explicit Graph(std::vector nodes) : nodes_(std::move(nodes)) {} + + // Breadth First Search + InfoBFS BFS(const Node& startNode) const; + std::deque PathBFS(const Node &start, const Node &finish) const; + + // Depth First Search + InfoDFS DFS() const; + // An alternate DFS that checks each node of the graph beginning at startNode + InfoDFS DFS(const Node &startNode) const; + // Visit function is used in both versions of DFS + void DFSVisit(int &time, const Node& startNode, InfoDFS &searchInfo) const; + // Topological sort, using DFS + std::vector TopologicalSort(const Node &startNode) const; + + // Returns a copy of a node with the number i within the graph + // + This uses the private, non-const accessor GetNode() and returns a copy + inline Node GetNodeCopy(int i) { return GetNode(i);} + // Return a constant iterator for reading node values + inline std::vector::const_iterator NodeBegin() { return nodes_.cbegin();} + +private: + // A non-const accessor for direct access to a node with the number value i + inline Node & GetNode(int i) + { return *std::find(nodes_.begin(), nodes_.end(), Node(i, {}));} + // For grabbing a const qualified node + inline const Node & GetNode(int i) const + { return *std::find(nodes_.begin(), nodes_.end(), Node(i, {}));} + + std::vector nodes_; +}; + +#endif // LIB_GRAPH_HPP