main(){ graph **adj_list; int n, m, n1, n2; //Creating the adjacency list scanf("%d %d", &n, &m); adj_list=create_empty_list(adj_list, n); //Creating edges int i; for(i=0;i<m;++i){ scanf("%d %d", &n1, &n2); create_edge(n1,n2,adj_list,n); create_edge(n2,n1,adj_list,n); } print_list(adj_list, n); //Marking elements as visited int *visited,*parent; visited=(int *)malloc(n*sizeof(int)); parent=(int *)malloc(n*sizeof(int)); for(i=0;i<n;++i){ visited[i]=0; parent[i]=-1; } //Printing the connected componenets printf("\n\nThe cycles are: \n"); for(i=0;i<n;++i){ if(visited[i]==0){ dfs_cycle(adj_list,i,visited,parent); } } }
bool dfs_cycle(vector<unordered_set<int>>& graph, int node, vector<bool>& onpath, vector<bool>& visited) { onpath[node] = visited[node] = true; //go through the adjcent list for this node for(int neigh : graph[node]) { if (onpath[neigh] || dfs_cycle(graph, neigh, onpath, visited)) return true; } return onpath[node] = false; }
void dfs_cycle(graph **adj, int x, int *visited, int *parent){ int id;//Temporarily store the id of element graph *temp;//Loop variable visited[x]=1;//Marking x as visited //Parsing through all the neighbours of x temp=adj[x]->next; while(temp!=NULL){ id=temp->id; if(visited[id]==0){ parent[id]=x; dfs_cycle(adj,id,visited,parent); } else if(visited[id]==1&&parent[id]!=x) //write statements for printing the cycle temp=temp->next; } }
bool canFinish(int numCourses, vector<pair<int, int>>& prerequisites) { //as the graph node value is int type, we use the node value to index // the nodes, for non-int value, maybe key_to_index is needed // also visited flags are accessed by node value // visited = true does not mean the cycle is detected!! // after all the adjacent nodes are dfsed, the onpath is set to // false. then if the adjacent nodes is still onpath but now get // to be dfsed, cycle is detected!! //adjacent list is represneted by unordered_set<int> vector<unordered_set<int>> graph = make_graph(numCourses, prerequisites); vector<bool> onpath(numCourses, false), visited(numCourses, false); //loop the vertices to perform DFS for(int i = 0; i < numCourses; i++) { if (!visited[i] && dfs_cycle(graph, i, onpath, visited)) return false; } return true; }