#cycle detection in undirected graphs

3 messages · Page 1 of 1 (latest)

uncut egret
#

https://practice.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1

The code I wrote.....

class Solution {
// Function to detect cycle in an undirected graph.
public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
// Code here

    boolean []visited = new boolean[V];
    
    for(int i =0; i<adj.size();i++){
        if(visited[i] == false){
            if(iscycleUtil(adj,i, -1, visited)){
                return true;
            }
        }
    }
    return false;
}

public boolean iscycleUtil( ArrayList<ArrayList<Integer>> adj, int current, int parent, boolean[] visited){
    visited[current] = true;
    
    for(int j =0; j<(adj.get(current)).size();j++){
       for(int i : adj.get(current)){
           if(visited[i] == false){
               if(iscycleUtil(adj,i,current,visited)){
                   return true;
               }
           }
           
           else if(visited[i] == true && i != parent){
               return true;
           }
       }
    }
    return false;
 } 

}

My test cases are failings, I am not getting where I went wrong.

Given an undirected graph with V vertices and E edges, check whether it contains any cycle or not. Graph is in the form of adjacency list where adj[i] contains all the nodes ith node is having edge with.
Example 1:
Input:  
V = 5, E = 5
adj

subtle wingBOT
#

This post has been reserved for your question.

Hey @uncut egret! Please use /close or the Close Post button above when you're finished. Please remember to follow the help guidelines. This post will be automatically closed after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.