Detect Cycle in Directed Graph

Given a directed graph, check whether the graph contains a cycle or not. Your function should return complete cycle path if given graph contains at least one cycle, else return null.

Java
Time complexity: O(V+E)
Space complexity: O(V) + O(h), where h is the longest path on call stack

public class DirectCycle<V>{


    public DirectCycle(){
    }

    public List<DirectedEdge<V>> getCycle(Digraph<V> g){
        if (g == null){
            throw new IllegalArgumentException("Invalid param passed!");
        }
        if (g.V() == 0 || g.E() == 0){
            return new ArrayList<>();
        }

        Set<V> whiteSet = new HashSet<>();//initial set of all vertexes
        Set<V> greySet = new HashSet<>();//vertexes processed on current stack
        Set<V> blackSet = new HashSet<>();//already processed vertexes
        Map<V,V> path = new HashMap<>();

        for (V v : g.getVertexes()){
            whiteSet.add(v);
        }

        while (!whiteSet.isEmpty()){
            V v = whiteSet.iterator().next();

            if (dfs(v, g, whiteSet, greySet, blackSet, path)){
                List<DirectedEdge<V>> cycle = buildCycle(v, path);
                return cycle;
            }
        }

        return null;
    }

    private List<DirectedEdge<V>> buildCycle(V v, Map<V, V> path) {
        List<DirectedEdge<V>> cycle = new ArrayList<>();
        V curr = v;
        while (path.containsKey(curr)){
            cycle.add(new DirectedEdge<V>(curr, path.get(curr)));
            V temp = path.get(curr);
            path.remove(curr);
            curr = temp;
        }
        return cycle;
    }

    private boolean dfs(V v, Digraph<V> g, Set<V> whiteSet, Set<V> greySet, Set<V> blackSet, Map<V,V> path){

        move(whiteSet, greySet, v);

        for (DirectedEdge<V> de : g.adj(v)){

            V neighb = de.to();
            path.put(v, neighb);

            if (blackSet.contains(neighb)){
                continue;
            }

            if (greySet.contains(neighb)){
                return true;
            }

            if (dfs(neighb, g, whiteSet, greySet, blackSet, path)){
                return true;
            }
        }

        move(greySet, blackSet, v);
        return false;

    }

    private void move(Set<V> source, Set<V> dest, V v){
        source.remove(v);
        dest.add(v);
    }

}

Check If Graph is Bipartite

A Bipartite Graph is a graph whose vertices can be divided into two independent sets, U and V such that every edge (u, v) either connects a vertex from U to V or a vertex from V to U. In other words, for every edge (u, v), either u belongs to U and v to V, or u belongs to V and v to U. We can also say that there is no edge that connects vertices of same set.
A bipartite graph is possible if the graph coloring is possible using two colors such that vertices in a set are colored with the same color.

Below code implements this algorithm.

Java
Time complexity: O(V+E)
Space complexity: O(V)

public class BipartiteGraphValidator {

    public static <V> boolean isBipartite(Graph<V> g){
        if (g == null || g.V() <= 1){
            return false;
        }

        Map<V, Boolean> coloredPath = new HashMap<>();//strongly connected graphs only
        Queue<V> q = new LinkedList<V>();

        V source = g.getVertexes().iterator().next();
        q.offer(source);
        coloredPath.put(source, Boolean.TRUE);

        while (q.size() > 0){
            V curr = q.poll();
            for (V neighb : g.adj(curr)){
                if (coloredPath.containsKey(neighb) && color(curr, coloredPath) == color(neighb, coloredPath)){
                    return false;
                }

                if (!coloredPath.containsKey(neighb)){
                    q.offer(neighb);
                }
                coloredPath.put(neighb, !color(curr, coloredPath));
            }
        }

        return true;
    }

    private static <V> boolean color(V v, Map<V, Boolean> coloredPath){
        return coloredPath.get(v);
    }
}

Lintcode. Topological Sort

Given an directed graph, a topological order of the graph nodes is defined as follow:

  • For each directed edge A -> B in graph, A must be before B in the order list.
  • The first node in the order can be any node in the graph with no nodes direct to it.

Find any topological order for the given graph. You can assume that there is at least one topological order in the graph and graph is of DAG type (directed acyclic graph).

Example

For given graph

dag

The topological order can be:

1, 3, 0, 2, 5
3, 1, 2, 5, 0

Topological sort is commonly used for dependencies resolution in processes like instruction scheduling or defining build order of compilation units. For more information, please watch Topological Sort by Prof. Sedgewick

Java (reverse DFS)
Time complexity: O(V + E), V – num of vertexes, E – num of edges
Space complexity: O(V) + O(E) (for recursive call stack), V – num of vertexes, E – num of edges

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */    
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        if (graph == null || graph.isEmpty()){
            return new ArrayList<>();
        }
        
        Stack<DirectedGraphNode> stack = new Stack<>();
        Set<Integer> seen = new HashSet<>();
        
        for (DirectedGraphNode node : graph){
            reverseDFS(node, seen, stack);     
        }
        
        Collections.reverse(stack);
        
        return new ArrayList<>(stack);
        
    }
    
    private void reverseDFS(DirectedGraphNode node, Set<Integer> seen, Stack<DirectedGraphNode> stack){
        if (seen.contains(node.label)){
            return;
        }
        
        for (DirectedGraphNode neighbour : node.neighbors){
            if (!seen.contains(neighbour.label)){
                reverseDFS(neighbour, seen, stack);    
            }
        }
        
        stack.push(node);
        seen.add(node.label);
    }
}

Java (BFS)
Time complexity: O(V*D)(to init degree map) + O(V + E), V – num of vertexes, D – max vertex degree, E – num of edges
Space complexity: O(V), V – num of vertexes

/**
 * Definition for Directed graph.
 * class DirectedGraphNode {
 *     int label;
 *     ArrayList<DirectedGraphNode> neighbors;
 *     DirectedGraphNode(int x) { label = x; neighbors = new ArrayList<DirectedGraphNode>(); }
 * };
 */
public class Solution {
    /**
     * @param graph: A list of Directed graph node
     * @return: Any topological order for the given graph.
     */    
    public ArrayList<DirectedGraphNode> topSort(ArrayList<DirectedGraphNode> graph) {
        // write your code here
        if (graph == null || graph.size() == 0){
            return new ArrayList<>();
        }
        
        Map<DirectedGraphNode, Integer> inDegreeMap = getInDegreeMap(graph);
        Queue<DirectedGraphNode> q = new LinkedList<>();
        
        for (DirectedGraphNode node : graph){
            if (!inDegreeMap.containsKey(node)){
                q.offer(node);
            }
        }
        
        if (q.isEmpty()){//graph has cycles, not possible to build topSort
            return new ArrayList<>();    
        }
        
        ArrayList<DirectedGraphNode> res = new ArrayList<>();
        
        while (!q.isEmpty()){
            DirectedGraphNode curr = q.poll();
            res.add(curr);
            for (DirectedGraphNode neighb : curr.neighbors){
                int inDegree = inDegreeMap.get(neighb);
                inDegreeMap.put(neighb, inDegree - 1);
                if (inDegree - 1 == 0){
                    q.offer(neighb);
                }
            }
        }
        
        return res;
        
        
    }
    
    private Map<DirectedGraphNode, Integer> getInDegreeMap(List<DirectedGraphNode> graph){
        Map<DirectedGraphNode, Integer> inDegreeMap = new HashMap<>();  
        for (DirectedGraphNode node : graph){
            for (DirectedGraphNode neighb : node.neighbors){
                if (!inDegreeMap.containsKey(neighb)){
                    inDegreeMap.put(neighb, 1);
                } else {
                    inDegreeMap.put(neighb, inDegreeMap.get(neighb) + 1);
                }
            }
        }
        
        return inDegreeMap;
    }
    
}