Wednesday, 8 Dec 2021

Check if a cycle exists between nodes S and T in an Undirected Graph with only S and T repeating

#include using namespace std;  void createGraph(vector& graph,                 vector& edges){    for (auto x : edges) {                          graph[x[0]].push_back(x[1]);        graph[x[1]].push_back(x[0]);    }}  bool findSimpleCycle(int cur,                     vector& graph,                     int start, int dest,                     vector& visited,                     bool flag){          if (!flag and cur == dest) {        dest = start;        flag = 1;    }                  if (flag and cur == dest) {        return true;    }      bool ans = 0;    visited[cur] = 1;    for (auto child : graph[cur]) {                                  if (!visited[child] or child == dest) {            ans = ans                  | findSimpleCycle(                        child, graph, start,                        dest, visited, flag);        }    }                  visited[cur] = 0;      return ans;}  int main(){    int nodes = 7;    vector edges        = { { 0, 1 }, { 1, 2 }, { 2, 3 },            { 3, 4 }, { 4, 5 }, { 5, 2 },            { 2, 6 }, { 6, 0 } };    int S = 0, T = 4;          vector graph(nodes);          vector visited(nodes);    createGraph(graph, edges);              if (findSimpleCycle(S, graph,                        S, T, visited, 0)) {        cout