Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // If there is multiple cycle print any of them, graph will be directed graph
- #include<bits/stdc++.h>
- using namespace std;
- vector<int>adj[100], cycle;
- int vis[100], pathvis[100];
- int dfs(int node){
- vis[node] = 1;
- pathvis[node] = 1;
- cycle.push_back(node);
- for(auto it: adj[node]){
- if(pathvis[it] == 1){
- // Cycle found
- int startindex = 0;
- while(cycle[startindex]!=it){
- startindex++;
- }
- for(int i = startindex; i <cycle.size(); i++){
- cout << cycle[i] << " ";
- }
- cout << it << endl;
- return true; // Stop DFS after finding the first cycle
- }
- else if(vis[it] == 0){
- if(dfs(it)==true){
- return true; // Stop DFS early if a cycle is found
- }
- }
- }
- pathvis[node] = 0;
- cycle.pop_back();
- return false;
- }
- int main(){
- int v, e;
- cin >> v >> e;
- for(int i = 0; i < e; i++){
- int x, y;
- cin >> x >> y;
- adj[x].push_back(y);
- }
- memset(vis, 0, sizeof(vis));
- memset(pathvis, 0, sizeof(pathvis));
- for(int i = 0; i < v; i++){
- if(vis[i] == 0){
- cycle.clear();
- dfs(i);
- break; //Stop after finding the first cycle
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment