1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92
|
// C++ program to detect cycle
// in an undirected graph
// using BFS.
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
void addEdge(vector<int> adj[], int u, int v)
{
adj[u].push_back(v);
adj[v].push_back(u);
}
bool isCyclicConntected(vector<int> adj[], int s, int V, vector<bool>& visited, vector<int>& bucket)
{
// Set parent vertex for every vertex as -1.
vector<int> parent(V, -1);
// Create a queue for BFS
queue<int> q;
// Mark the current node as
// visited and enqueue it
visited[s] = true;
q.push(s);
while (!q.empty()) {
// Dequeue a vertex from queue and print it
int u = q.front();
q.pop();
// Get all adjacent vertices of the dequeued
// vertex u. If a adjacent has not been visited,
// then mark it visited and enqueue it. We also
// mark parent so that parent is not considered
// for cycle.
for (auto v : adj[u])
{
cout << v;
if (find(bucket.begin(), bucket.end(), v) != bucket.end()){
if (!visited[v])
{
visited[v] = true;
q.push(v);
parent[v] = u;
}
else if (parent[u] != v)
return true;
}
}
}
return false;
}
bool isCyclicDisconntected(vector<int> adj[], int V, vector<int>& bucket)
{
// Mark all the vertices as not visited
vector<bool> visited(V, false);
for (int i = 0; i < V; i++)
if (!visited[i] && isCyclicConntected(adj, i, V, visited, bucket))
return true;
return false;
}
// Driver program to test methods of graph class
int main()
{
int const V = 4;
vector<int> adj[V];
addEdge(adj, 0, 1);
addEdge(adj, 1, 2);
addEdge(adj, 2, 0);
addEdge(adj, 2, 3);
vector<int> bucket;
bucket.push_back(0);
bucket.push_back(3);
if (isCyclicDisconntected(adj, V, bucket))
cout << "Yes";
else
cout << "No";
return 0;
}
|