From 6922d2fa3928f8d3488a4421c00bda6a07d32026 Mon Sep 17 00:00:00 2001 From: Siddharth6780 <63189333+Siddharth6780@users.noreply.github.com> Date: Fri, 2 Oct 2020 00:01:53 +0530 Subject: [PATCH] Create Cycle_Detection.cpp --- Cycle_Detection.cpp | 57 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 Cycle_Detection.cpp diff --git a/Cycle_Detection.cpp b/Cycle_Detection.cpp new file mode 100644 index 0000000..5385e83 --- /dev/null +++ b/Cycle_Detection.cpp @@ -0,0 +1,57 @@ +#include +using namespace std; +#define ll long long +#define fio ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL) +#define endl '\n' +#define mod 1000000007 +bool Cycle_Detection_helper(map>m, bool *visited, int src, int parent) { + visited[src] = true; + for (auto nbr : m[src]) { + if (visited[nbr] == false) { + bool cycle_found = Cycle_Detection_helper(m, visited, nbr, src); + if (cycle_found) { + return true; + } + } + else if (nbr != parent) { + return true; + } + } + + return false; +} +bool Cycle_Detection(map>m, int n) { + bool visited[n]; + for (int i = 0; i < n; i++) { + visited[i] = false; + } + int src; + cin >> src; + return Cycle_Detection_helper(m, visited, src, -1); +} +int main() { + fio; + int n; + cin >> n; + map>m; + for (int i = 0; i < n; i++) { + int x, y; + cin >> x >> y; + m[x].push_back(y); + m[y].push_back(x); + } + if (Cycle_Detection(m, n)) { + cout << "Yes" << endl; + } + else { + cout << "No" << endl; + } + for (auto p : m) { + cout << p.first << "-->"; + for (auto p1 : p.second) { + cout << p1 << " "; + } + cout << endl; + } + return 0; +}