From 80c709b673c73ca150e5508343fcde6b2be2695c Mon Sep 17 00:00:00 2001 From: NaiJi Date: Mon, 20 Sep 2021 15:37:15 +0300 Subject: [PATCH] 6.1 --- 6.1/graph.cpp | 94 +++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 94 insertions(+) create mode 100644 6.1/graph.cpp diff --git a/6.1/graph.cpp b/6.1/graph.cpp new file mode 100644 index 0000000..c946faf --- /dev/null +++ b/6.1/graph.cpp @@ -0,0 +1,94 @@ +#include +#include +#include + +template +struct ListNode +{ + T value; + std::shared_ptr> next; +}; + +template +struct List +{ + std::shared_ptr> head; +}; + +template +struct GraphNode +{ + T value; + List>> relations; +}; + +using T = char; +using GraphNodeT = std::shared_ptr>; +using ListNodeT = ListNode>>; + +bool step(const GraphNodeT& node, std::size_t counter, std::size_t& min, const GraphNodeT& goal) +{ + if (!node) + return false; + + std::cout << "Step: " << node->value << ";\n"; + + if (node == goal) + { + min = counter; + return true; + } + + bool found = false; + + if (counter < min) + { + auto iter_node = node->relations.head; + while (iter_node) + { + found = found || step(iter_node->value, counter + 1, min, goal); + iter_node = iter_node->next; + } + } + + return found; +} + +std::size_t findPath(const GraphNodeT& root, const GraphNodeT& goal) +{ + if (!root || !goal) + return 0; + + std::size_t min = std::numeric_limits::max(); + + return step(root, 0, min, goal) + ? min + : 0; +} + +int main() +{ + auto s = std::make_shared>(GraphNode{'s', {}}); + auto e1 = std::make_shared>(GraphNode{'1', {}}); + auto e2 = std::make_shared>(GraphNode{'2', {}}); + auto e3 = std::make_shared>(GraphNode{'3', {}}); + auto e4 = std::make_shared>(GraphNode{'4', {}}); + auto f = std::make_shared>(GraphNode{'f', {}}); + + s->relations.head = std::make_shared(); + s->relations.head->value = e1; + s->relations.head->next = std::make_shared(); + s->relations.head->next->value = e2; + e1->relations.head = std::make_shared(); + e1->relations.head->value = f; + e1->relations.head->next = std::make_shared(); + e1->relations.head->next->value = e3; + e2->relations.head = std::make_shared(); + e2->relations.head->value = e3; + e2->relations.head->next = std::make_shared(); + e2->relations.head->next->value = e4; + e4->relations.head = std::make_shared(); + e4->relations.head->value = f; + + std::cout << "Min: " << findPath(s, f) << "\n\n\n\n"; +}