From f3631deaca2c8115f30f8ead287152498d58c63d Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Sun, 21 Apr 2024 21:55:04 +0200 Subject: [PATCH] =?UTF-8?q?cpp:=20add=20=C2=AB1971.=20Find=20if=20Path=20E?= =?UTF-8?q?xists=20in=20Graph=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- cpp/find-if-path-exists-in-graph.cpp | 35 ++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 cpp/find-if-path-exists-in-graph.cpp diff --git a/cpp/find-if-path-exists-in-graph.cpp b/cpp/find-if-path-exists-in-graph.cpp new file mode 100644 index 0000000..60d3966 --- /dev/null +++ b/cpp/find-if-path-exists-in-graph.cpp @@ -0,0 +1,35 @@ +#include + +struct Solution { + using edges_t = std::vector>; + + bool validPath(int n, const edges_t &edges, int source, int destination) { + std::vector visited(n); + visited[source] = true; + + bool changed; + do { + changed = iterate(edges, visited); + } while (changed && !visited[destination]); + + return visited[destination]; + } + + private: + bool iterate(const edges_t &edges, std::vector &visited) { + bool changed = false; + + for (const auto &edge : edges) { + auto [u, v] = std::tie(edge[0], edge[1]); + if (visited[u] == visited[v]) { + continue; + } + + visited[u] = true; + visited[v] = true; + changed = true; + } + + return changed; + } +};