Program:-
#include <bits/stdc++.h>
using namespace std;
int cycle=0;
void dfs(vector<int>*vec,vector<bool>&vis,int index,vector<bool>&visited){
if(vis[index]==true) return;
vis[index]=true;
visited[index]=true;
//cout<<index<<" ";
for(int i=0;i<vec[index].size();i++){
if(visited[vec[index][i]]) cycle=1;
if(vis[vec[index][i]]==false){
dfs(vec,vis,vec[index][i],visited);
}
}
}
int main() {
int n,m;
cin>>n>>m;
vector<int>vec[n];
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
vec[a].push_back(b);
}
vector<bool>vis(n,false);
for(int i=0;i<n;i++){
if(vis[i]==false){
vector<bool>visited(n,false);
dfs(vec,vis,i,visited);
}
}
if(cycle) cout<<"Cycle";
else cout<<"Not Cycle";
return 0;
}
#include <bits/stdc++.h>
using namespace std;
int cycle=0;
void dfs(vector<int>*vec,vector<bool>&vis,int index,vector<bool>&visited){
if(vis[index]==true) return;
vis[index]=true;
visited[index]=true;
//cout<<index<<" ";
for(int i=0;i<vec[index].size();i++){
if(visited[vec[index][i]]) cycle=1;
if(vis[vec[index][i]]==false){
dfs(vec,vis,vec[index][i],visited);
}
}
}
int main() {
int n,m;
cin>>n>>m;
vector<int>vec[n];
for(int i=0;i<m;i++){
int a,b;
cin>>a>>b;
vec[a].push_back(b);
}
vector<bool>vis(n,false);
for(int i=0;i<n;i++){
if(vis[i]==false){
vector<bool>visited(n,false);
dfs(vec,vis,i,visited);
}
}
if(cycle) cout<<"Cycle";
else cout<<"Not Cycle";
return 0;
}
No comments:
Post a Comment