3

I am trying to detect cycle in an undirected graph. I am using DFS to detect the same. For any node, I will visit through all connected nodes. If the child node is already visited and its not parent of current node, We have a cycle in graph.

I wrote below code :

public boolean isCyclicUtil(int current, boolean[] visited, int parent, ArrayList<ArrayList<Integer>> adj) {
    visited[current] = true;
    Iterator<Integer> it = adj.get(current).iterator();

    while (it.hasNext()) {
        int nextNode = it.next();
        if (!visited[nextNode]) {
            return isCyclicUtil(nextNode, visited, current, adj);
        } else {
            if (nextNode != parent)
                return true;
        }
    }
    return false;
}

public boolean isCycle(int V, ArrayList<ArrayList<Integer>> adj) {
    boolean[] visited = new boolean[V];
    for (int i = 0; i < V; i++) {
        if (!visited[i] && isCyclicUtil(i, visited, -1, adj)) {
            return true;
        }
    }
    return false;
}

It is failing for certain test cases. I am not able to figure out what is wrong with the code. Please help me understand bug in my code.

  • 1
    *Please share the link of the problem as well. If possible, share any input instance where it is going wrong.* I did test it against few inputs, it did work correctly on them. – AKSingh Apr 27 '21 at 07:43
  • https://practice.geeksforgeeks.org/problems/detect-cycle-in-an-undirected-graph/1 – Vivek Kumar Apr 27 '21 at 10:39

1 Answers1

2

Instead of visiting all adjacent vertices, you stop exploring them after visiting the first adjacent vertex that has not been visited yet because of the return statement:

if (!visited[nextNode]) {
    return isCyclicUtil(nextNode, visited, current, adj);
}

Your search space from a single isCyclicUtil execution essentially becomes a path, and some vertices will not be visited. They will of course be visited in some later iteration within isCycle function, but it might be a good exercise to understand why some cycles might not be detected this way.

Fixing is easy - you want to return only if you have actually found a cycle.

stiar
  • 358
  • 1
  • 7
  • Thanks a lot. changing the code as mentioned below worked: `code` if (!visited[nextNode]) { if(isCyclicUtil(nextNode, visited, current, adj)) return true; } else { if (nextNode != parent) return true; } `code` – Vivek Kumar Apr 27 '21 at 10:49