@@ -0,0 +1,1864 @@
+package com.graphs;%0A%0Aimport java.util.HashSet;%0Aimport java.util.Set;%0A%0A/**%0A * Detect if a given graph have a cycle or not%0A * %0A * @author STEPHANE MIGUEL KAKANAKOU (Skakanakou@gmail.com)%0A *%0A */%0Apublic class DetectCycle %7B%0A%0A    /**%0A     * Detect if the given graph contains a cycle.%0A     * %0A     * @param graph%0A     * %0A     * @return true if the graph contains cycle and false if not.%0A     */%0A    public static boolean haveCycle(GraphAdjacencyListRepresentation graph) %7B%0A        /* contains the vertices that hasn't been explored yet. */%0A        Set%3CInteger%3E whiteSet = new HashSet%3C%3E();%0A%0A        /* contains the vertices that are currently being explored. */%0A        Set%3CInteger%3E graySet = new HashSet%3C%3E();%0A%0A        /* contains the vertices that have been already explored. */%0A        Set%3CInteger%3E blackSet = new HashSet%3C%3E();%0A%0A        int V_Size = graph.getV_Size();%0A        for (int u = 0; u %3C V_Size; u++) %7B%0A            whiteSet.add(u);%0A        %7D%0A        boolean cycle = false;%0A        for (int u = 0; u %3C V_Size; u++) %7B%0A            cycle = cycle %7C hasCycle(graph, u, false, whiteSet, graySet, blackSet);%0A        %7D%0A        return cycle;%0A    %7D%0A%0A    private static boolean hasCycle(GraphAdjacencyListRepresentation graph, int u, boolean detectCycle,%0A            Set%3CInteger%3E whiteSet, Set%3CInteger%3E graySet, Set%3CInteger%3E blackSet) %7B%0A        if (detectCycle)%0A            return detectCycle;%0A        whiteSet.remove(new Integer(u));%0A        graySet.add(u);%0A        boolean b = false;%0A        for (int v : graph.getAdjNode(u)) %7B%0A%0A            if (graySet.contains(new Integer(v))) %7B%0A                return true;%0A            %7D%0A%0A            if (!blackSet.contains(new Integer(v))) %7B%0A                b = b %7C hasCycle(graph, v, b, whiteSet, graySet, blackSet);%0A            %7D%0A        %7D%0A        graySet.remove(new Integer(u));%0A        blackSet.add(u);%0A        return b;%0A    %7D%0A%0A%7D%0A

Add DetectCycle to detect cycle in graph