#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"; }