Created
April 5, 2022 05:29
-
-
Save devil-cyber/d497cd8fdd12d033423c54f34c04301d to your computer and use it in GitHub Desktop.
Connected Component in Directed Graph
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include<iostream> | |
#include<list> | |
#include<vector> | |
using namespace std; | |
class Graph{ | |
int V; | |
list<int> *l; | |
public: | |
Graph(int v){ | |
V = v; | |
l = new list<int>[V]; | |
} | |
void addEdge(int x, int y, bool undir = false){ | |
l[x].push_back(y); | |
if(undir) | |
l[y].push_back(x); | |
} | |
bool dfs(int src, vector<bool> &visted, vector<bool> &stack){ | |
visted[src] = true; | |
stack[src] = true; | |
for(auto node:l[src]){ | |
if(stack[node]) | |
return true; | |
else if(!visted[node]){ | |
bool iscycle = dfs(node, visted, stack); | |
if(iscycle) | |
return true; | |
} | |
} | |
stack[src] = false; | |
return false; | |
} | |
}; | |
int main(){ | |
Graph g1(5); | |
vector<bool> visted(5, false); | |
vector<bool> stack(5, false); | |
g1.addEdge(1, 0); | |
g1.addEdge(0, 2); | |
g1.addEdge(2, 1); | |
g1.addEdge(0, 3); | |
g1.addEdge(3, 4); | |
cout<<g1.dfs(0, visted, stack)<<endl; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment