简体   繁体   中英

Graph: How to detect cycles in a undirectd graph using DFS

Following is my DFS implementation, now I want to implement it such that I can detect if there are any cycles present in a graph or not.(The below code is basically used to find the number of connected elements)

#include <iostream>
#include <vector>
using namespace std;

vector <int> adj[10];
int visited[10];
bool flag=false;

void dfs(int s) {
    visited[s] = 0;
    for(int i = 0;i < adj[s].size();++i)    {
     if(visited[adj[s][i]] == -1)
         dfs(adj[s][i]);
     else if (visited[adj[s][i]] ==1){
        flag=true;
        // cout<<"g";  
        return;
     }
    }
    visited[s]=1;
}

void initialize() {
    for(int i = 0;i < 10;++i)
     visited[i] = -1;
}

int main() {
    int nodes, edges, x, y ;
    cin >> nodes;                       //Number of nodes
    cin >> edges;                       //Number of edges
    for(int i = 0;i < edges;++i) {
     cin >> x >> y;     
     adj[x].push_back(y);                   //Edge from vertex x to vertex y
     adj[y].push_back(x);                   //Edge from vertex y to vertex x
    }

    initialize();                           //Initialize all nodes as not visited

    for(int i = 1;i <= nodes;++i) {
     if(visited[i] == false)     {
         dfs(i);
     }

    }
    if (flag)
        cout<<"Graph contains cycles"<<endl;
    else
        cout<<"No cycles"<<endl;
    return 0;
}

I am not sure how to implement it, could anyone help me with it.

Edit : I have tried to implement it. Don't know where I am going wrong

I've changed the loop after the initialization call to:

for(int i = 0;i < nodes;++i) {
  if(visited[i] == -1)     {
    dfs(i);
  }
}

Your code did not start checking because each element in the visited was set to -1 and therefore skipped. So with this change it does work.

I suggest to look at size of your global variables adj and visted , make them local if possible. When 11 or more nodes are entered this code will stop working.

Edit for question “Can you tell me how do I check for disconnected graph?”

Change the same loop to this:

int nr_of_graphs = 0;
for(int i = 0;i < nodes;++i) {
  if(visited[i] == -1)     {
    ++nr_of_graphs;
    dfs(i);
  }
}
cout << "Nr of disconnected subgraphs " << nr_of_graphs << endl; 

dfs(i) is called for each not yet visited node. So count the amount of times this function is called from main, gives the number of disconnected subgraphs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM