Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Solution {
- public:
- // Function to detect cycle in an undirected graph.
- bool dfs(int node, int parent, vector<int> adj[], vector<bool> & visited) {
- visited[node] = true;
- for(int neigh : adj[node]) {
- if(!visited[neigh] ) {
- if(dfs(neigh, node, adj, visited)) {
- return true;
- }
- }
- else if(neigh != parent) {
- return true;
- }
- }
- return false;
- }
- bool isCycle(int V, vector<int> adj[]) {
- bool res = false;
- vector<bool> visited(V + 2, false);
- for(int i = 0; i < V; i++) {
- if(!visited[i]) {
- if(dfs(i, -1, adj, visited)) {
- return true;
- }
- }
- }
- return false;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement